• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 <mutex>
21 #include <securec.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24 
25 #include "ability_manager_errors.h"
26 #include "ability_window_configuration.h"
27 #include "accesstoken_kit.h"
28 #include "app_mem_info.h"
29 #include "app_mgr_service.h"
30 #include "app_process_data.h"
31 #include "app_state_observer_manager.h"
32 #include "app_utils.h"
33 #include "appfreeze_manager.h"
34 #include "application_state_observer_stub.h"
35 #include "appspawn_mount_permission.h"
36 #include "bundle_constants.h"
37 #include "common_event.h"
38 #include "common_event_manager.h"
39 #include "common_event_support.h"
40 #include "datetime_ex.h"
41 #include "distributed_data_mgr.h"
42 #include "freeze_util.h"
43 #include "hilog_wrapper.h"
44 #include "hitrace_meter.h"
45 #include "in_process_call_wrapper.h"
46 #include "ipc_skeleton.h"
47 #include "iremote_object.h"
48 #include "iservice_registry.h"
49 #include "itest_observer.h"
50 #ifdef SUPPORT_GRAPHICS
51 #include "locale_config.h"
52 #endif
53 #include "os_account_manager_wrapper.h"
54 #include "parameter.h"
55 #include "parameters.h"
56 #include "perf_profile.h"
57 #include "permission_constants.h"
58 #include "permission_verification.h"
59 #include "system_ability_definition.h"
60 #include "string_ex.h"
61 #include "time_util.h"
62 #include "ui_extension_utils.h"
63 #include "uri_permission_manager_client.h"
64 #ifdef APP_MGR_SERVICE_APPMS
65 #include "net_conn_client.h"
66 #endif
67 #include "application_info.h"
68 #include "meminfo.h"
69 
70 namespace OHOS {
71 namespace AppExecFwk {
72 using namespace OHOS::Rosen;
73 using namespace OHOS::Security;
74 
75 namespace {
76 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
77     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
78         HILOG_ERROR("The caller is not system-app, can not use system-api");                   \
79         return AAFwk::ERR_NOT_SYSTEM_APP;                                                             \
80     }
81 
82 #define CHECK_IS_SA_CALL(listener)                                                                  \
83     auto instance = AAFwk::PermissionVerification::GetInstance();                                   \
84     if (listener == nullptr || instance == nullptr || appRunningStatusModule_ == nullptr) {         \
85         HILOG_ERROR("Listener or getInstance is nullptr or appRunningStatusModule_ is nullptr");    \
86         return ERR_INVALID_VALUE;                                                                   \
87     }                                                                                               \
88     if (!instance->IsSACall()) {                                                                    \
89         HILOG_ERROR("CallerToken not SA.");                                                         \
90         return ERR_PERMISSION_DENIED;                                                               \
91     }
92 
93 // NANOSECONDS mean 10^9 nano second
94 constexpr int64_t NANOSECONDS = 1000000000;
95 // MICROSECONDS mean 10^6 milli second
96 constexpr int64_t MICROSECONDS = 1000000;
97 // Kill process timeout setting
98 constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000;
99 // Kill process delay time setting
100 constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200;
101 // delay register focus listener to wms
102 constexpr int REGISTER_FOCUS_DELAY = 5000;
103 constexpr int REGISTER_VISIBILITY_DELAY = 5000;
104 // Max render process number limitation for phone device.
105 constexpr int PHONE_MAX_RENDER_PROCESS_NUM = 40;
106 const std::string CLASS_NAME = "ohos.app.MainThread";
107 const std::string FUNC_NAME = "main";
108 const std::string RENDER_PARAM = "invalidparam";
109 const std::string COLD_START = "coldStart";
110 const std::string PERF_CMD = "perfCmd";
111 const std::string DEBUG_CMD = "debugCmd";
112 const std::string ENTER_SANDBOX = "sandboxApp";
113 const std::string DLP_PARAMS_INDEX = "ohos.dlp.params.index";
114 const std::string PERMISSION_INTERNET = "ohos.permission.INTERNET";
115 const std::string PERMISSION_MANAGE_VPN = "ohos.permission.MANAGE_VPN";
116 const std::string PERMISSION_ACCESS_BUNDLE_DIR = "ohos.permission.ACCESS_BUNDLE_DIR";
117 const std::string PERMISSION_GET_BUNDLE_RESOURCES = "ohos.permission.GET_BUNDLE_RESOURCES";
118 const std::string DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
119 const std::string SUPPORT_ISOLATION_MODE = "persist.bms.supportIsolationMode";
120 const std::string SUPPORT_SERVICE_EXT_MULTI_PROCESS = "component.startup.extension.multiprocess.enable";
121 const std::string SERVICE_EXT_MULTI_PROCESS_WHITE_LIST = "component.startup.extension.multiprocess.whitelist";
122 const std::string SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard";
123 const std::string DEBUG_APP = "debugApp";
124 const std::string SERVICE_EXTENSION = ":ServiceExtension";
125 const std::string KEEP_ALIVE = ":KeepAlive";
126 const std::string PARAM_SPECIFIED_PROCESS_FLAG = "ohoSpecifiedProcessFlag";
127 const int32_t SIGNAL_KILL = 9;
128 constexpr int32_t USER_SCALE = 200000;
129 #define ENUM_TO_STRING(s) #s
130 #define APP_ACCESS_BUNDLE_DIR 0x20
131 #define APP_OVERLAY_FLAG 0x100
132 #define GET_BUNDLE_RESOURCES_FLAG 0x200
133 
134 constexpr int32_t BASE_USER_RANGE = 200000;
135 
136 constexpr int32_t MAX_RESTART_COUNT = 3;
137 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
138 
139 constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01);
140  // Error code for already exist render.
141 constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100;
142  // Error code for reaching render process number limitation.
143 constexpr ErrCode ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION = APPMGR_ERR_OFFSET + 101;
144 constexpr char EVENT_KEY_UID[] = "UID";
145 constexpr char EVENT_KEY_PID[] = "PID";
146 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
147 constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME";
148 constexpr char EVENT_KEY_MESSAGE[] = "MSG";
149 
150 // Developer mode param
151 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
152 
153 // Msg length is less than 48 characters
154 const std::string EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!";
155 const std::string EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!";
156 const std::string EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT = "Add Ability Stage TimeOut!";
157 const std::string EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT = "Start Specified Process Timeout!";
158 const std::string EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!";
159 const std::string EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = "Start Process Specified Ability TimeOut!";
160 const std::string EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!";
161 
162 const std::string SYSTEM_BASIC = "system_basic";
163 const std::string SYSTEM_CORE = "system_core";
164 const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
165 const std::string PROCESS_EXIT_EVENT_TASK = "Send Process Exit Event Task";
166 
167 constexpr int32_t ROOT_UID = 0;
168 constexpr int32_t FOUNDATION_UID = 5523;
169 constexpr int32_t QUICKFIX_UID = 5524;
170 constexpr int32_t DEFAULT_USER_ID = 0;
171 
172 constexpr int32_t BLUETOOTH_GROUPID = 1002;
173 
174 #ifdef APP_MGR_SERVICE_APPMS
175 constexpr int32_t NETSYS_SOCKET_GROUPID = 1097;
176 #endif
177 
178 constexpr int32_t DEFAULT_INVAL_VALUE = -1;
179 
GetUserIdByUid(int32_t uid)180 int32_t GetUserIdByUid(int32_t uid)
181 {
182     return uid / BASE_USER_RANGE;
183 }
184 
VerifyPermission(const BundleInfo & bundleInfo,const std::string & permissionName)185 bool VerifyPermission(const BundleInfo &bundleInfo, const std::string &permissionName)
186 {
187     if (permissionName.empty() || bundleInfo.reqPermissions.empty()) {
188         HILOG_ERROR("permissionName or reqPermissions is empty.");
189         return false;
190     }
191 
192     bool ret = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
193         [permissionName] (const auto &reqPermission) {
194             if (permissionName == reqPermission) {
195                 return true;
196             }
197             return false;
198         });
199     if (!ret) {
200         HILOG_INFO("Not request permission %{public}s", permissionName.c_str());
201         return ret;
202     }
203 
204     auto token = bundleInfo.applicationInfo.accessTokenId;
205     int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, permissionName, false);
206     if (result != Security::AccessToken::PERMISSION_GRANTED) {
207         HILOG_ERROR("StartProcess permission %{public}s not granted", permissionName.c_str());
208         return false;
209     }
210 
211     return true;
212 }
213 
ShouldUseMultipleRenderProcess(std::string & deviceType)214 bool ShouldUseMultipleRenderProcess(std::string& deviceType) {
215     // The "default" device type means phone.
216     return deviceType == "tablet" || deviceType == "pc" || deviceType == "2in1" ||
217            deviceType == "default" || deviceType == "phone";
218 }
219 
220 }  // namespace
221 
222 using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED;
223 using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
224 
AppMgrServiceInner()225 AppMgrServiceInner::AppMgrServiceInner()
226     : appProcessManager_(std::make_shared<AppProcessManager>()),
227       remoteClientManager_(std::make_shared<RemoteClientManager>()),
228       appRunningManager_(std::make_shared<AppRunningManager>()),
229       configuration_(std::make_shared<Configuration>()),
230       appDebugManager_(std::make_shared<AppDebugManager>()),
231       appRunningStatusModule_(std::make_shared<AbilityRuntime::AppRunningStatusModule>())
232 {}
233 
Init()234 void AppMgrServiceInner::Init()
235 {
236     InitGlobalConfiguration();
237     AddWatchParameter();
238     supportIsolationMode_ = OHOS::system::GetParameter(SUPPORT_ISOLATION_MODE, "false");
239     supportServiceExtMultiProcess_ = OHOS::system::GetParameter(SUPPORT_SERVICE_EXT_MULTI_PROCESS, "false");
240     ParseServiceExtMultiProcessWhiteList();
241     deviceType_ = OHOS::system::GetDeviceType();
242     DelayedSingleton<AppStateObserverManager>::GetInstance()->Init();
243 }
244 
~AppMgrServiceInner()245 AppMgrServiceInner::~AppMgrServiceInner()
246 {}
247 
StartSpecifiedProcess(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo)248 void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)
249 {
250     HILOG_DEBUG("call.");
251     BundleInfo bundleInfo;
252     HapModuleInfo hapModuleInfo;
253     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
254 
255     int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
256     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
257         return;
258     }
259 
260     std::string processName;
261     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
262     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, processName);
263     HILOG_DEBUG("processName = %{public}s", processName.c_str());
264     auto mainAppRecord =
265         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
266     if (mainAppRecord != nullptr) {
267         HILOG_DEBUG("main process exists.");
268         mainAppRecord->SetScheduleNewProcessRequestState(true, want, hapModuleInfo.moduleName);
269         auto moduleRecord = mainAppRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
270         if (!moduleRecord) {
271             HILOG_DEBUG("module record is nullptr, add modules");
272             std::vector<HapModuleInfo> hapModules = { hapModuleInfo };
273             mainAppRecord->AddModules(appInfo, hapModules);
274             mainAppRecord->AddAbilityStageBySpecifiedProcess(appInfo->bundleName);
275             return;
276         }
277         HILOG_DEBUG("schedule new process request.");
278         mainAppRecord->ScheduleNewProcessRequest(want, hapModuleInfo.moduleName);
279         return;
280     }
281     HILOG_DEBUG("main process do not exists.");
282     if (startSpecifiedAbilityResponse_) {
283         startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, "");
284     }
285 }
286 
LoadAbility(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const std::shared_ptr<AAFwk::Want> & want)287 void AppMgrServiceInner::LoadAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
288     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
289     const std::shared_ptr<AAFwk::Want> &want)
290 {
291     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
292     HILOG_INFO("name:%{public}s.", abilityInfo->name.c_str());
293     if (!CheckLoadAbilityConditions(token, abilityInfo, appInfo)) {
294         HILOG_ERROR("CheckLoadAbilityConditions failed");
295         return;
296     }
297     if (abilityInfo->type == AbilityType::PAGE) {
298         AbilityRuntime::FreezeUtil::LifecycleFlow flow = {token, AbilityRuntime::FreezeUtil::TimeoutState::LOAD};
299         auto entry = std::to_string(AbilityRuntime::TimeUtil::SystemTimeMillisecond()) +
300             "; AppMgrServiceInner::LoadAbility; the load lifecycle.";
301         AbilityRuntime::FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
302     }
303 
304     if (!appRunningManager_) {
305         HILOG_ERROR("appRunningManager_ is nullptr");
306         return;
307     }
308 
309     BundleInfo bundleInfo;
310     HapModuleInfo hapModuleInfo;
311     int32_t appIndex = (want == nullptr) ? 0 : want->GetIntParam(DLP_PARAMS_INDEX, 0);
312     if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
313         HILOG_ERROR("GetBundleAndHapInfo failed");
314         return;
315     }
316 
317     std::string processName;
318     MakeProcessName(abilityInfo, appInfo, hapModuleInfo, appIndex, processName);
319     HILOG_DEBUG("processName = %{public}s", processName.c_str());
320 
321     std::shared_ptr<AppRunningRecord> appRecord;
322     // for isolation process
323     std::string specifiedProcessFlag = "";
324     bool isPcDevice = (deviceType_ == "pc" || deviceType_ == "2in1");
325     bool isUIAbility = (abilityInfo->type == AppExecFwk::AbilityType::PAGE && abilityInfo->isStageBasedModel);
326     bool isSpecifiedProcess = abilityInfo->isolationProcess && isPcDevice && isUIAbility;
327     if (isSpecifiedProcess) {
328         specifiedProcessFlag = want->GetStringParam(PARAM_SPECIFIED_PROCESS_FLAG);
329         HILOG_INFO("specifiedProcessFlag = %{public}s", specifiedProcessFlag.c_str());
330     }
331     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name,
332         processName, appInfo->uid, bundleInfo, specifiedProcessFlag);
333     if (!appRecord) {
334         HILOG_DEBUG("appRecord null");
335         bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
336         if (!appExistFlag) {
337             NotifyAppRunningStatusEvent(
338                 bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
339         }
340         appRecord = CreateAppRunningRecord(token, preToken, appInfo, abilityInfo,
341             processName, bundleInfo, hapModuleInfo, want);
342         if (!appRecord) {
343             HILOG_ERROR("CreateAppRunningRecord failed, appRecord is nullptr");
344             return;
345         }
346         if (isSpecifiedProcess && !specifiedProcessFlag.empty()) {
347             appRecord->SetSpecifiedProcessFlag(specifiedProcessFlag);
348         }
349         if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, hapModuleInfo)) {
350             appRecord->SetKeepAliveAppState(false, false);
351             HILOG_INFO("The process %{public}s will not keepalive", hapModuleInfo.process.c_str());
352         }
353         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::COLD);
354         auto callRecord = GetAppRunningRecordByAbilityToken(preToken);
355         if (callRecord != nullptr) {
356             auto launchReson = (want == nullptr) ? 0 : want->GetIntParam("ohos.ability.launch.reason", 0);
357             HILOG_DEBUG("req: %{public}d, proc: %{public}s, call:%{public}d,%{public}s", launchReson,
358                 appInfo->name.c_str(), appRecord->GetCallerPid(), callRecord->GetBundleName().c_str());
359         }
360         uint32_t startFlags = (want == nullptr) ? 0 : BuildStartFlags(*want, *abilityInfo);
361         int32_t bundleIndex = (want == nullptr) ? 0 : want->GetIntParam(DLP_PARAMS_INDEX, 0);
362         StartProcess(abilityInfo->applicationName, processName, startFlags, appRecord,
363             appInfo->uid, bundleInfo, appInfo->bundleName, bundleIndex, appExistFlag);
364         std::string perfCmd = (want == nullptr) ? "" : want->GetStringParam(PERF_CMD);
365         bool isSandboxApp = (want == nullptr) ? false : want->GetBoolParam(ENTER_SANDBOX, false);
366         (void)StartPerfProcess(appRecord, perfCmd, "", isSandboxApp);
367     } else {
368         HILOG_INFO("have apprecord");
369         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::MULTI_INSTANCE);
370         int32_t requestProcCode = (want == nullptr) ? 0 : want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0);
371         if (requestProcCode != 0 && appRecord->GetRequestProcCode() == 0) {
372             appRecord->SetRequestProcCode(requestProcCode);
373             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessReused(appRecord);
374         }
375         StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want);
376     }
377     PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
378     PerfProfile::GetInstance().Dump();
379     PerfProfile::GetInstance().Reset();
380     appRecord->UpdateAbilityState(token, AbilityState::ABILITY_STATE_CREATE);
381 }
382 
CheckLoadAbilityConditions(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo)383 bool AppMgrServiceInner::CheckLoadAbilityConditions(const sptr<IRemoteObject> &token,
384     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo)
385 {
386     if (!token || !abilityInfo || !appInfo) {
387         HILOG_ERROR("param error");
388         return false;
389     }
390     if (abilityInfo->name.empty() || appInfo->name.empty()) {
391         HILOG_ERROR("error abilityInfo or appInfo");
392         return false;
393     }
394     if (abilityInfo->applicationName != appInfo->name) {
395         HILOG_ERROR("abilityInfo and appInfo have different appName, don't load for it");
396         return false;
397     }
398 
399     return true;
400 }
401 
MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,std::string & processName) const402 void AppMgrServiceInner::MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
403     const std::shared_ptr<ApplicationInfo> &appInfo, std::string &processName) const
404 {
405     if (abilityInfo == nullptr || appInfo == nullptr) {
406         HILOG_ERROR("Ability info or app info is nullptr.");
407         return;
408     }
409 
410     if (supportServiceExtMultiProcess_.compare("true") != 0) {
411         return;
412     }
413 
414     if (processName == appInfo->bundleName &&
415         abilityInfo->extensionAbilityType == ExtensionAbilityType::SERVICE) {
416         auto iter = std::find(
417             serviceExtensionWhiteList_.begin(), serviceExtensionWhiteList_.end(), processName);
418         if (iter != serviceExtensionWhiteList_.end()) {
419             HILOG_DEBUG("Application is in whiteList, skipping!");
420             return;
421         }
422 
423         processName += SERVICE_EXTENSION;
424         if (appInfo->keepAlive) {
425             processName += KEEP_ALIVE;
426         }
427     }
428 }
429 
MakeProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,int32_t appIndex,std::string & processName) const430 void AppMgrServiceInner::MakeProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
431     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, int32_t appIndex,
432     std::string &processName) const
433 {
434     if (!abilityInfo || !appInfo) {
435         HILOG_ERROR("param error");
436         return;
437     }
438     if (!abilityInfo->process.empty()) {
439         HILOG_DEBUG("Process not null");
440         processName = abilityInfo->process;
441         return;
442     }
443     MakeProcessName(appInfo, hapModuleInfo, processName);
444     MakeServiceExtProcessName(abilityInfo, appInfo, processName);
445     if (appIndex != 0) {
446         processName += std::to_string(appIndex);
447     }
448 }
449 
MakeProcessName(const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,std::string & processName) const450 void AppMgrServiceInner::MakeProcessName(
451     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, std::string &processName) const
452 {
453     if (!appInfo) {
454         HILOG_ERROR("appInfo nill");
455         return;
456     }
457     // check after abilityInfo, because abilityInfo contains extension process.
458     if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()
459         && hapModuleInfo.process != appInfo->bundleName) {
460         processName = hapModuleInfo.process;
461         HILOG_INFO("Stage mode, Make processName:%{public}s", processName.c_str());
462         return;
463     }
464     bool isRunInIsolationMode = CheckIsolationMode(hapModuleInfo);
465     if (hapModuleInfo.isStageBasedModel && isRunInIsolationMode) {
466         processName = appInfo->bundleName;
467         processName.append(":");
468         processName.append(hapModuleInfo.name);
469         return;
470     }
471     if (!appInfo->process.empty()) {
472         processName = appInfo->process;
473         return;
474     }
475     processName = appInfo->bundleName;
476 }
477 
IsMainProcess(const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo) const478 bool AppMgrServiceInner::IsMainProcess(const std::shared_ptr<ApplicationInfo> &appInfo,
479     const HapModuleInfo &hapModuleInfo) const
480 {
481     if (!appInfo) {
482         return true;
483     }
484     if (hapModuleInfo.process.empty()) {
485         return true;
486     }
487     if (!appInfo->process.empty()) {
488         if (hapModuleInfo.process == appInfo->process) {
489             return true;
490         }
491     } else {
492         if (hapModuleInfo.process == appInfo->bundleName) {
493             return true;
494         }
495     }
496     return false;
497 }
498 
CheckIsolationMode(const HapModuleInfo & hapModuleInfo) const499 bool AppMgrServiceInner::CheckIsolationMode(const HapModuleInfo &hapModuleInfo) const
500 {
501     IsolationMode isolationMode = hapModuleInfo.isolationMode;
502     if (supportIsolationMode_.compare("true") == 0) {
503         switch (isolationMode) {
504             case IsolationMode::ISOLATION_FIRST:
505                 return true;
506             case IsolationMode::ISOLATION_ONLY:
507                 return true;
508             default:
509                 return false;
510         }
511     }
512     return false;
513 }
514 
GetBundleAndHapInfo(const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo,int32_t appIndex) const515 bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo,
516     const std::shared_ptr<ApplicationInfo> &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo,
517     int32_t appIndex) const
518 {
519     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
520     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
521     if (bundleMgrHelper == nullptr) {
522         HILOG_ERROR("The bundleMgrHelper is nullptr.");
523         return false;
524     }
525 
526     auto userId = GetUserIdByUid(appInfo->uid);
527     HILOG_DEBUG("UserId:%{public}d.", userId);
528     bool bundleMgrResult;
529     if (appIndex == 0) {
530         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(appInfo->bundleName,
531             BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
532     } else {
533         bundleMgrResult = (IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(appInfo->bundleName,
534             appIndex, userId, bundleInfo)) == 0);
535     }
536 
537     if (!bundleMgrResult) {
538         HILOG_ERROR("GetBundleInfo is fail.");
539         return false;
540     }
541     if (appIndex == 0) {
542         bundleMgrResult = bundleMgrHelper->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo);
543     } else {
544         bundleMgrResult = (bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0);
545     }
546     if (!bundleMgrResult) {
547         HILOG_ERROR("GetHapModuleInfo is fail.");
548         return false;
549     }
550 
551     return true;
552 }
553 
AttachApplication(const pid_t pid,const sptr<IAppScheduler> & appScheduler)554 void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &appScheduler)
555 {
556     HILOG_DEBUG("called");
557     if (pid <= 0) {
558         HILOG_ERROR("invalid pid:%{public}d", pid);
559         return;
560     }
561     auto appRecord = GetAppRunningRecordByPid(pid);
562     if (!appRecord) {
563         HILOG_ERROR("no such appRecord");
564         return;
565     }
566     auto applicationInfo = appRecord->GetApplicationInfo();
567     AAFwk::EventInfo eventInfo;
568     if (!applicationInfo) {
569         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
570     } else {
571         eventInfo.bundleName = applicationInfo->name;
572         eventInfo.versionName = applicationInfo->versionName;
573         eventInfo.versionCode = applicationInfo->versionCode;
574     }
575     std::string connector = "##";
576     std::string traceName = __PRETTY_FUNCTION__ + connector + eventInfo.bundleName;
577     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
578     if (!appScheduler) {
579         HILOG_ERROR("app client is null");
580         return;
581     }
582     HILOG_INFO("attach, pid:%{public}d.", pid);
583     sptr<AppDeathRecipient> appDeathRecipient = new (std::nothrow) AppDeathRecipient();
584     if (appDeathRecipient == nullptr) {
585         HILOG_ERROR("Failed to create death recipient.");
586         return;
587     }
588     appDeathRecipient->SetTaskHandler(taskHandler_);
589     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
590     auto object = appScheduler->AsObject();
591     if (!object || !object->AddDeathRecipient(appDeathRecipient)) {
592         HILOG_ERROR("Failed to add DeathRecipient for %{public}s.", appRecord->GetProcessName().c_str());
593         return;
594     }
595 
596     appRecord->SetAppDeathRecipient(appDeathRecipient);
597     appRecord->SetApplicationClient(appScheduler);
598     if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
599         LaunchApplication(appRecord);
600     }
601     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
602     eventInfo.processName = appRecord->GetProcessName();
603     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_ATTACH, HiSysEventType::BEHAVIOR, eventInfo);
604 }
605 
LaunchApplication(const std::shared_ptr<AppRunningRecord> & appRecord)606 void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
607 {
608     if (!appRecord) {
609         HILOG_ERROR("appRecord is null");
610         return;
611     }
612     auto applicationInfo = appRecord->GetApplicationInfo();
613     std::string bundleName = "";
614     if (!applicationInfo) {
615         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
616     } else {
617         bundleName = applicationInfo->name;
618     }
619     std::string connector = "##";
620     std::string traceName = __PRETTY_FUNCTION__ + connector + bundleName;
621     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
622 
623     if (!configuration_) {
624         HILOG_ERROR("configuration_ is null");
625         return;
626     }
627 
628     if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
629         HILOG_ERROR("wrong app state:%{public}d", appRecord->GetState());
630         return;
631     }
632 
633     appRecord->LaunchApplication(*configuration_);
634     appRecord->SetState(ApplicationState::APP_STATE_READY);
635     int restartResidentProcCount = MAX_RESTART_COUNT;
636     appRecord->SetRestartResidentProcCount(restartResidentProcCount);
637 
638     // There is no ability when the empty resident process starts
639     // The status of all resident processes is ready
640     // There is no process of switching the foreground, waiting for his first ability to start
641     if (appRecord->IsEmptyKeepAliveApp()) {
642         appRecord->AddAbilityStage();
643         return;
644     }
645 
646     if (appRecord->IsStartSpecifiedAbility()) {
647         appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
648         return;
649     }
650     appRecord->LaunchPendingAbilities();
651     SendAppLaunchEvent(appRecord);
652 }
653 
AddAbilityStageDone(const int32_t recordId)654 void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId)
655 {
656     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
657     if (!appRecord) {
658         HILOG_ERROR("get app record failed");
659         return;
660     }
661     appRecord->AddAbilityStageDone();
662 }
663 
ApplicationForegrounded(const int32_t recordId)664 void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId)
665 {
666     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
667     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
668     if (!appRecord || (!appRecord->IsUpdateStateFromService()
669         && appRecord->GetApplicationPendingState() != ApplicationPendingState::FOREGROUNDING)) {
670         HILOG_ERROR("get app record failed");
671         return;
672     }
673     ApplicationState appState = appRecord->GetState();
674     if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) {
675         appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND);
676         bool needNotifyApp = appRunningManager_->IsApplicationFirstForeground(*appRecord);
677         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, false);
678         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
679     } else {
680         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
681             appRecord->GetName().c_str(), static_cast<ApplicationState>(appState));
682     }
683     appRecord->SetUpdateStateFromService(false);
684     appRecord->SetApplicationPendingState(ApplicationPendingState::READY);
685     appRecord->PopForegroundingAbilityTokens();
686 
687     // push the foregrounded app front of RecentAppList.
688     PushAppFront(recordId);
689     HILOG_DEBUG("application is foregrounded");
690     AAFwk::EventInfo eventInfo;
691     auto applicationInfo = appRecord->GetApplicationInfo();
692     if (!applicationInfo) {
693         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
694     } else {
695         eventInfo.bundleName = applicationInfo->name;
696         eventInfo.versionName = applicationInfo->versionName;
697         eventInfo.versionCode = applicationInfo->versionCode;
698         eventInfo.bundleType = static_cast<int32_t>(applicationInfo->bundleType);
699     }
700     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
701     eventInfo.processName = appRecord->GetProcessName();
702     eventInfo.processType = static_cast<int32_t>(appRecord->GetProcessType());
703     int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
704     auto callerRecord = GetAppRunningRecordByPid(callerPid);
705     if (callerRecord != nullptr) {
706         eventInfo.callerBundleName = callerRecord->GetBundleName();
707     } else {
708         HILOG_ERROR("callerRecord is nullptr, can not get callerBundleName.");
709     }
710     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_FOREGROUND, HiSysEventType::BEHAVIOR, eventInfo);
711 }
712 
ApplicationBackgrounded(const int32_t recordId)713 void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId)
714 {
715     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
716     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
717     if (!appRecord || !appRecord->IsUpdateStateFromService()) {
718         HILOG_ERROR("get app record failed");
719         return;
720     }
721     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
722         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
723         bool needNotifyApp = !AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
724             && !AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
725             && appRunningManager_->IsApplicationBackground(appRecord->GetBundleName());
726         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND, needNotifyApp, false);
727         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
728     } else {
729         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
730             appRecord->GetName().c_str(), static_cast<ApplicationState>(appRecord->GetState()));
731     }
732     appRecord->SetUpdateStateFromService(false);
733     if (appRecord->GetApplicationPendingState() == ApplicationPendingState::BACKGROUNDING) {
734         appRecord->SetApplicationPendingState(ApplicationPendingState::READY);
735     }
736 
737     HILOG_INFO("application is backgrounded");
738     AAFwk::EventInfo eventInfo;
739     auto applicationInfo = appRecord->GetApplicationInfo();
740     if (!applicationInfo) {
741         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
742     } else {
743         eventInfo.bundleName = applicationInfo->name;
744         eventInfo.versionName = applicationInfo->versionName;
745         eventInfo.versionCode = applicationInfo->versionCode;
746         eventInfo.bundleType = static_cast<int32_t>(applicationInfo->bundleType);
747     }
748     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
749     eventInfo.processName = appRecord->GetProcessName();
750     eventInfo.processType = static_cast<int32_t>(appRecord->GetProcessType());
751     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_BACKGROUND, HiSysEventType::BEHAVIOR, eventInfo);
752 }
753 
ApplicationTerminated(const int32_t recordId)754 void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
755 {
756     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
757     if (!appRunningManager_) {
758         HILOG_ERROR("appRunningManager_ is nullptr");
759         return;
760     }
761 
762     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
763     if (!appRecord) {
764         HILOG_ERROR("get app record failed");
765         return;
766     }
767     appRecord->ApplicationTerminated();
768     // Maybe can't get in here
769     if (appRecord->IsKeepAliveApp()) {
770         return;
771     }
772     if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
773         HILOG_ERROR("current state is not background");
774         return;
775     }
776 
777     KillRenderProcess(appRecord);
778     KillChildProcess(appRecord);
779     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
780     appRecord->RemoveAppDeathRecipient();
781     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED);
782     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false);
783     appRunningManager_->RemoveAppRunningRecordById(recordId);
784     RemoveAppFromRecentListById(recordId);
785     AAFwk::EventInfo eventInfo;
786     auto applicationInfo = appRecord->GetApplicationInfo();
787     if (!applicationInfo) {
788         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
789     } else {
790         eventInfo.bundleName = applicationInfo->name;
791         eventInfo.versionName = applicationInfo->versionName;
792         eventInfo.versionCode = applicationInfo->versionCode;
793     }
794     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
795     eventInfo.processName = appRecord->GetProcessName();
796     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
797 
798     ApplicationTerminatedSendProcessEvent(appRecord);
799 
800     auto uid = appRecord->GetUid();
801     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
802 }
803 
UpdateApplicationInfoInstalled(const std::string & bundleName,const int uid)804 int32_t AppMgrServiceInner::UpdateApplicationInfoInstalled(const std::string &bundleName, const int uid)
805 {
806     if (!appRunningManager_) {
807         HILOG_ERROR("The appRunningManager_ is nullptr.");
808         return ERR_NO_INIT;
809     }
810 
811     int32_t result = VerifyRequestPermission();
812     if (result != ERR_OK) {
813         HILOG_ERROR("Permission verification failed.");
814         return result;
815     }
816 
817     if (remoteClientManager_ == nullptr) {
818         HILOG_ERROR("The remoteClientManager_ fail.");
819         return ERR_NO_INIT;
820     }
821 
822     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
823     if (bundleMgrHelper == nullptr) {
824         HILOG_ERROR("The bundleMgrHelper is nullptr.");
825         return ERR_NO_INIT;
826     }
827     auto userId = GetUserIdByUid(uid);
828     ApplicationInfo appInfo;
829     HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetApplicationInfo");
830     bool bundleMgrResult = bundleMgrHelper->GetApplicationInfo(bundleName,
831         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo);
832     if (!bundleMgrResult) {
833         HILOG_ERROR("Failed to get applicationInfo.");
834         return ERR_INVALID_OPERATION;
835     }
836 
837     HILOG_DEBUG("uid value is %{public}d", uid);
838     result = appRunningManager_->ProcessUpdateApplicationInfoInstalled(appInfo);
839     if (result != ERR_OK) {
840         HILOG_INFO("The process corresponding to the package name did not start.");
841     }
842 
843     return result;
844 }
845 
KillApplication(const std::string & bundleName)846 int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName)
847 {
848     if (!appRunningManager_) {
849         HILOG_ERROR("appRunningManager_ is nullptr");
850         return ERR_NO_INIT;
851     }
852 
853     if (CheckCallerIsAppGallery()) {
854         return KillApplicationByBundleName(bundleName);
855     }
856 
857     auto result = VerifyProcessPermission(bundleName);
858     if (result != ERR_OK) {
859         HILOG_ERROR("Permission verification failed.");
860         return result;
861     }
862 
863     return KillApplicationByBundleName(bundleName);
864 }
865 
KillApplicationByUid(const std::string & bundleName,const int uid)866 int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid)
867 {
868     if (!appRunningManager_) {
869         HILOG_ERROR("appRunningManager_ is nullptr");
870         return ERR_NO_INIT;
871     }
872 
873     int32_t result = ERR_OK;
874     if (!CheckCallerIsAppGallery()) {
875         result = VerifyProcessPermission(bundleName);
876         if (result != ERR_OK) {
877             HILOG_ERROR("Permission verification failed.");
878             return result;
879         }
880     }
881 
882     int64_t startTime = SystemTimeMillisecond();
883     std::list<pid_t> pids;
884     if (remoteClientManager_ == nullptr) {
885         HILOG_ERROR("The remoteClientManager_ is nullptr.");
886         return ERR_NO_INIT;
887     }
888     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
889     if (bundleMgrHelper == nullptr) {
890         HILOG_ERROR("The bundleMgrHelper is nullptr.");
891         return ERR_NO_INIT;
892     }
893     HILOG_INFO("uid value is %{public}d", uid);
894     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
895         HILOG_INFO("not start");
896         return result;
897     }
898     if (WaitForRemoteProcessExit(pids, startTime)) {
899         HILOG_INFO("The remote process exited successfully ");
900         return result;
901     }
902     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
903         result = KillProcessByPid(*iter);
904         if (result < 0) {
905             HILOG_ERROR("KillApplication failed for bundleName:%{public}s pid:%{public}d", bundleName.c_str(), *iter);
906             return result;
907         }
908     }
909     return result;
910 }
911 
SendProcessExitEventTask(pid_t pid,time_t exitTime,int32_t count)912 void AppMgrServiceInner::SendProcessExitEventTask(pid_t pid, time_t exitTime, int32_t count)
913 {
914     auto exitResult = !ProcessExist(pid);
915     constexpr int32_t EXIT_SUCESS = 0;
916     constexpr int32_t EXIT_FAILED = -1;
917 
918     if (exitResult) {
919         AAFwk::EventInfo eventInfo;
920         eventInfo.time = exitTime;
921         eventInfo.exitResult = EXIT_SUCESS;
922         eventInfo.pid = pid;
923         AAFwk::EventReport::SendAppEvent(AAFwk::EventName::PROCESS_EXIT, HiSysEventType::BEHAVIOR, eventInfo);
924         HILOG_INFO("time : %{public}" PRId64 ", exitResult : %{public}d, pid : %{public}d",
925             eventInfo.time, eventInfo.exitResult, eventInfo.pid);
926         return;
927     }
928 
929     if (--count <= 0) {
930         AAFwk::EventInfo eventInfo;
931         eventInfo.time = exitTime;
932         eventInfo.exitResult = EXIT_FAILED;
933         eventInfo.pid = pid;
934         AAFwk::EventReport::SendAppEvent(AAFwk::EventName::PROCESS_EXIT, HiSysEventType::BEHAVIOR, eventInfo);
935         HILOG_INFO("time : %{public}" PRId64 ", exitResult : %{public}d, pid : %{public}d",
936             eventInfo.time, eventInfo.exitResult, eventInfo.pid);
937         return;
938     }
939 
940     auto sendEventTask = [inner = shared_from_this(), pid, exitTime, count] () {
941         inner->SendProcessExitEventTask(pid, exitTime, count);
942     };
943     taskHandler_->SubmitTask(sendEventTask, PROCESS_EXIT_EVENT_TASK, KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
944 }
945 
SendProcessExitEvent(pid_t pid)946 void AppMgrServiceInner::SendProcessExitEvent(pid_t pid)
947 {
948     HILOG_DEBUG("called.");
949     time_t currentTime;
950     time(&currentTime);
951     constexpr int32_t RETRY_COUNT = 5;
952     SendProcessExitEventTask(pid, currentTime, RETRY_COUNT);
953     return;
954 }
955 
KillApplicationSelf()956 int32_t AppMgrServiceInner::KillApplicationSelf()
957 {
958     if (!appRunningManager_) {
959         HILOG_ERROR("appRunningManager_ is nullptr");
960         return ERR_NO_INIT;
961     }
962 
963     auto callerPid = IPCSkeleton::GetCallingPid();
964     auto appRecord = GetAppRunningRecordByPid(callerPid);
965     if (!appRecord) {
966         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
967         return ERR_INVALID_VALUE;
968     }
969     auto bundleName = appRecord->GetBundleName();
970     return KillApplicationByBundleName(bundleName);
971 }
972 
KillApplicationByBundleName(const std::string & bundleName)973 int32_t AppMgrServiceInner::KillApplicationByBundleName(const std::string &bundleName)
974 {
975     int result = ERR_OK;
976     int64_t startTime = SystemTimeMillisecond();
977     std::list<pid_t> pids;
978 
979     if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids)) {
980         HILOG_ERROR("The process corresponding to the package name did not start");
981         return result;
982     }
983     if (WaitForRemoteProcessExit(pids, startTime)) {
984         HILOG_DEBUG("The remote process exited successfully ");
985         NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
986         return result;
987     }
988     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
989         result = KillProcessByPid(*iter);
990         if (result < 0) {
991             HILOG_ERROR("KillApplicationSelf is failed for bundleName:%{public}s, pid: %{public}d",
992                 bundleName.c_str(), *iter);
993             return result;
994         }
995     }
996     NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
997     return result;
998 }
999 
KillApplicationByUserId(const std::string & bundleName,const int userId)1000 int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleName, const int userId)
1001 {
1002     if (!appRunningManager_) {
1003         HILOG_ERROR("appRunningManager_ is nullptr");
1004         return ERR_NO_INIT;
1005     }
1006     CHECK_CALLER_IS_SYSTEM_APP;
1007     if (VerifyAccountPermission(
1008         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES, userId) == ERR_PERMISSION_DENIED) {
1009         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1010         return ERR_PERMISSION_DENIED;
1011     }
1012 
1013     if (remoteClientManager_ == nullptr) {
1014         HILOG_ERROR("remoteClientManager_ fail");
1015         return ERR_NO_INIT;
1016     }
1017     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1018     if (bundleMgrHelper == nullptr) {
1019         HILOG_ERROR("The bundleMgrHelper is nullptr.");
1020         return ERR_NO_INIT;
1021     }
1022 
1023     return KillApplicationByUserIdLocked(bundleName, userId);
1024 }
1025 
KillApplicationByUserIdLocked(const std::string & bundleName,const int userId)1026 int32_t AppMgrServiceInner::KillApplicationByUserIdLocked(const std::string &bundleName, const int userId)
1027 {
1028     if (!appRunningManager_) {
1029         HILOG_ERROR("appRunningManager_ is nullptr");
1030         return ERR_NO_INIT;
1031     }
1032 
1033     int result = ERR_OK;
1034     int64_t startTime = SystemTimeMillisecond();
1035     std::list<pid_t> pids;
1036     if (remoteClientManager_ == nullptr) {
1037         HILOG_ERROR("remoteClientManager_ is nullptr.");
1038         return ERR_NO_INIT;
1039     }
1040     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1041     if (bundleMgrHelper == nullptr) {
1042         HILOG_ERROR("The bundleMgrHelper is nullptr.");
1043         return ERR_NO_INIT;
1044     }
1045 
1046     HILOG_INFO("userId value is %{public}d", userId);
1047     int uid = IN_PROCESS_CALL(bundleMgrHelper->GetUidByBundleName(bundleName, userId));
1048     HILOG_INFO("uid value is %{public}d", uid);
1049     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
1050         HILOG_INFO("The process corresponding to the package name did not start.");
1051         return result;
1052     }
1053     if (WaitForRemoteProcessExit(pids, startTime)) {
1054         HILOG_INFO("The remote process exited successfully ");
1055         return result;
1056     }
1057     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1058         result = KillProcessByPid(*iter);
1059         if (result < 0) {
1060             HILOG_ERROR("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter);
1061             return result;
1062         }
1063     }
1064     return result;
1065 }
1066 
ClearUpApplicationData(const std::string & bundleName,int32_t callerUid,pid_t callerPid,const int32_t userId)1067 int32_t AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName,
1068     int32_t callerUid, pid_t callerPid, const int32_t userId)
1069 {
1070     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1071     int32_t newUserId = userId;
1072     if (userId == DEFAULT_INVAL_VALUE) {
1073         newUserId = GetUserIdByUid(callerUid);
1074     }
1075     HILOG_INFO("userId:%{public}d", userId);
1076     return ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, newUserId);
1077 }
1078 
ClearUpApplicationDataBySelf(int32_t callerUid,pid_t callerPid,int32_t userId)1079 int32_t AppMgrServiceInner::ClearUpApplicationDataBySelf(int32_t callerUid, pid_t callerPid, int32_t userId)
1080 {
1081     if (!appRunningManager_) {
1082         HILOG_ERROR("appRunningManager_ is nullptr");
1083         return ERR_NO_INIT;
1084     }
1085     auto appRecord = GetAppRunningRecordByPid(callerPid);
1086     if (!appRecord) {
1087         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
1088         return ERR_INVALID_VALUE;
1089     }
1090     auto callerbundleName = appRecord->GetBundleName();
1091     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1092     int32_t newUserId = userId;
1093     if (userId == DEFAULT_INVAL_VALUE) {
1094         newUserId = GetUserIdByUid(callerUid);
1095     }
1096     return ClearUpApplicationDataByUserId(callerbundleName, callerUid, callerPid, newUserId, true);
1097 }
1098 
ClearUpApplicationDataByUserId(const std::string & bundleName,int32_t callerUid,pid_t callerPid,const int userId,bool isBySelf)1099 int32_t AppMgrServiceInner::ClearUpApplicationDataByUserId(
1100     const std::string &bundleName, int32_t callerUid, pid_t callerPid, const int userId, bool isBySelf)
1101 {
1102     if (callerPid <= 0) {
1103         HILOG_ERROR("invalid callerPid:%{public}d", callerPid);
1104         return ERR_INVALID_OPERATION;
1105     }
1106     if (callerUid < 0) {
1107         HILOG_ERROR("invalid callerUid:%{public}d", callerUid);
1108         return ERR_INVALID_OPERATION;
1109     }
1110     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1111     if (bundleMgrHelper == nullptr) {
1112         HILOG_ERROR("The bundleMgrHelper is nullptr.");
1113         return ERR_INVALID_OPERATION;
1114     }
1115 
1116     // request to clear user information permission.
1117     auto tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, 0);
1118     int32_t result = AccessToken::AccessTokenKit::ClearUserGrantedPermissionState(tokenId);
1119     if (result) {
1120         HILOG_ERROR("ClearUserGrantedPermissionState failed, ret:%{public}d", result);
1121         return ERR_PERMISSION_DENIED;
1122     }
1123     // 2.delete bundle side user data
1124     if (!IN_PROCESS_CALL(bundleMgrHelper->CleanBundleDataFiles(bundleName, userId))) {
1125         HILOG_ERROR("Delete bundle side user data is fail");
1126         return ERR_INVALID_OPERATION;
1127     }
1128     // 3.kill application
1129     // 4.revoke user rights
1130     result = isBySelf ? KillApplicationSelf() : KillApplicationByUserId(bundleName, userId);
1131     if (result < 0) {
1132         HILOG_ERROR("Kill Application by bundle name is fail");
1133         return ERR_INVALID_OPERATION;
1134     }
1135     // 5.revoke uri permission rights
1136     auto ret = IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().RevokeAllUriPermissions(tokenId));
1137     if (ret != ERR_OK) {
1138         HILOG_ERROR("Revoke all uri permissions is failed");
1139         return ret;
1140     }
1141     auto dataMgr = OHOS::DistributedKv::DistributedDataMgr();
1142     auto dataRet = dataMgr.ClearAppStorage(bundleName, userId, 0, tokenId);
1143     if (dataRet != 0) {
1144         HILOG_WARN("Distributeddata clear app storage failed, bundleName:%{public}s", bundleName.c_str());
1145     }
1146     NotifyAppStatusByCallerUid(bundleName, userId, callerUid,
1147         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
1148     return ERR_OK;
1149 }
1150 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)1151 int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
1152 {
1153     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1154     // check permission
1155     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
1156         const auto &appRecord = item.second;
1157         if (!appRecord->GetSpawned()) {
1158             continue;
1159         }
1160         if (isPerm) {
1161             GetRunningProcesses(appRecord, info);
1162         } else {
1163             auto applicationInfo = appRecord->GetApplicationInfo();
1164             if (!applicationInfo) {
1165                 continue;
1166             }
1167             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
1168             auto tokenId = applicationInfo->accessTokenId;
1169             if (callingTokenId == tokenId) {
1170                 GetRunningProcesses(appRecord, info);
1171             }
1172         }
1173     }
1174     return ERR_OK;
1175 }
1176 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)1177 int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
1178 {
1179     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
1180         ERR_PERMISSION_DENIED) {
1181         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1182         return ERR_PERMISSION_DENIED;
1183     }
1184 
1185     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
1186         const auto &appRecord = item.second;
1187         if (!appRecord->GetSpawned()) {
1188             continue;
1189         }
1190         int32_t userIdTemp = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
1191         if (userIdTemp == userId) {
1192             GetRunningProcesses(appRecord, info);
1193         }
1194     }
1195     return ERR_OK;
1196 }
1197 
GetProcessRunningInformation(RunningProcessInfo & info)1198 int32_t AppMgrServiceInner::GetProcessRunningInformation(RunningProcessInfo &info)
1199 {
1200     if (!appRunningManager_) {
1201         HILOG_ERROR("appRunningManager_ is nullptr");
1202         return ERR_NO_INIT;
1203     }
1204     auto callerPid = IPCSkeleton::GetCallingPid();
1205     auto appRecord = GetAppRunningRecordByPid(callerPid);
1206     if (!appRecord) {
1207         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
1208         return ERR_INVALID_VALUE;
1209     }
1210     GetRunningProcess(appRecord, info);
1211     return ERR_OK;
1212 }
1213 
GetAllRenderProcesses(std::vector<RenderProcessInfo> & info)1214 int32_t AppMgrServiceInner::GetAllRenderProcesses(std::vector<RenderProcessInfo> &info)
1215 {
1216     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1217     // check permission
1218     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
1219         const auto &appRecord = item.second;
1220         if (isPerm) {
1221             GetRenderProcesses(appRecord, info);
1222         } else {
1223             auto applicationInfo = appRecord->GetApplicationInfo();
1224             if (!applicationInfo) {
1225                 continue;
1226             }
1227             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
1228             auto tokenId = applicationInfo->accessTokenId;
1229             if (callingTokenId == tokenId) {
1230                 GetRenderProcesses(appRecord, info);
1231             }
1232         }
1233     }
1234     return ERR_OK;
1235 }
1236 
NotifyMemoryLevel(int32_t level)1237 int32_t AppMgrServiceInner::NotifyMemoryLevel(int32_t level)
1238 {
1239     HILOG_INFO("AppMgrServiceInner start");
1240 
1241     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
1242     if (!isSaCall) {
1243         HILOG_ERROR("callerToken not SA %{public}s", __func__);
1244         return ERR_INVALID_VALUE;
1245     }
1246     if (!(level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_MODERATE ||
1247         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_CRITICAL ||
1248         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_LOW)) {
1249         HILOG_ERROR("Level value error!");
1250         return ERR_INVALID_VALUE;
1251     }
1252     if (!appRunningManager_) {
1253         HILOG_ERROR("appRunningManager nullptr!");
1254         return ERR_INVALID_VALUE;
1255     }
1256 
1257     return appRunningManager_->NotifyMemoryLevel(level);
1258 }
1259 
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)1260 int32_t AppMgrServiceInner::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
1261 {
1262     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
1263     if (!isSaCall) {
1264         HILOG_ERROR("callerToken not SA %{public}s", __func__);
1265         return ERR_INVALID_VALUE;
1266     }
1267     if (pid < 0) {
1268         HILOG_ERROR("pid is illegal!");
1269         return ERR_INVALID_VALUE;
1270     }
1271     if (!appRunningManager_) {
1272         HILOG_ERROR("appRunningManager nullptr!");
1273         return ERR_INVALID_VALUE;
1274     }
1275     return appRunningManager_->DumpHeapMemory(pid, mallocInfo);
1276 }
1277 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)1278 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
1279     std::vector<RunningProcessInfo> &info)
1280 {
1281     RunningProcessInfo runningProcessInfo;
1282     GetRunningProcess(appRecord, runningProcessInfo);
1283     info.emplace_back(runningProcessInfo);
1284 }
1285 
GetRunningProcess(const std::shared_ptr<AppRunningRecord> & appRecord,RunningProcessInfo & info)1286 void AppMgrServiceInner::GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
1287     RunningProcessInfo &info)
1288 {
1289     info.processName_ = appRecord->GetProcessName();
1290     info.pid_ = appRecord->GetPriorityObject()->GetPid();
1291     info.uid_ = appRecord->GetUid();
1292     info.state_ = static_cast<AppProcessState>(appRecord->GetState());
1293     info.isContinuousTask = appRecord->IsContinuousTask();
1294     info.isKeepAlive = appRecord->IsKeepAliveApp();
1295     info.isFocused = appRecord->GetFocusFlag();
1296     info.startTimeMillis_ = appRecord->GetAppStartTime();
1297     appRecord->GetBundleNames(info.bundleNames);
1298     info.processType_ = appRecord->GetProcessType();
1299     info.extensionType_ = appRecord->GetExtensionType();
1300 }
1301 
GetRenderProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RenderProcessInfo> & info)1302 void AppMgrServiceInner::GetRenderProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
1303     std::vector<RenderProcessInfo> &info)
1304 {
1305     auto renderRecordMap = appRecord->GetRenderRecordMap();
1306     if (renderRecordMap.empty()) {
1307         return;
1308     }
1309     for (auto iter : renderRecordMap) {
1310         auto renderRecord = iter.second;
1311         if (renderRecord != nullptr) {
1312             RenderProcessInfo renderProcessInfo;
1313             renderProcessInfo.bundleName_ = renderRecord->GetHostBundleName();
1314             renderProcessInfo.processName_ = renderRecord->GetProcessName();
1315             renderProcessInfo.pid_ = renderRecord->GetPid();
1316             renderProcessInfo.uid_ = renderRecord->GetUid();
1317             renderProcessInfo.hostUid_ = renderRecord->GetHostUid();
1318             info.emplace_back(renderProcessInfo);
1319         }
1320     }
1321 }
1322 
KillProcessByPid(const pid_t pid) const1323 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid) const
1324 {
1325     int32_t ret = -1;
1326     if (pid > 0) {
1327         HILOG_INFO("kill pid %{public}d", pid);
1328         ret = kill(pid, SIGNAL_KILL);
1329     }
1330     AAFwk::EventInfo eventInfo;
1331     auto appRecord = GetAppRunningRecordByPid(pid);
1332     if (!appRecord) {
1333         return ret;
1334     }
1335     auto applicationInfo = appRecord->GetApplicationInfo();
1336     if (!applicationInfo) {
1337         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
1338     } else {
1339         eventInfo.bundleName = applicationInfo->name;
1340         eventInfo.versionName = applicationInfo->versionName;
1341         eventInfo.versionCode = applicationInfo->versionCode;
1342     }
1343     if (ret >= 0) {
1344         int64_t killTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
1345             system_clock::now().time_since_epoch()).count();
1346         killedPorcessMap_.emplace(killTime, appRecord->GetProcessName());
1347     }
1348     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
1349     eventInfo.processName = appRecord->GetProcessName();
1350     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
1351     return ret;
1352 }
1353 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)1354 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
1355 {
1356     int64_t delayTime = SystemTimeMillisecond() - startTime;
1357     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
1358         if (CheckAllProcessExist(pids)) {
1359             return true;
1360         }
1361         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
1362         delayTime = SystemTimeMillisecond() - startTime;
1363     }
1364     return false;
1365 }
1366 
GetAllPids(std::list<pid_t> & pids)1367 bool AppMgrServiceInner::GetAllPids(std::list<pid_t> &pids)
1368 {
1369     for (const auto &appTaskInfo : appProcessManager_->GetRecentAppList()) {
1370         if (appTaskInfo) {
1371             auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
1372             if (appRecord) {
1373                 pids.push_back(appTaskInfo->GetPid());
1374                 appRecord->ScheduleProcessSecurityExit();
1375             }
1376         }
1377     }
1378     return (pids.empty() ? false : true);
1379 }
1380 
ProcessExist(pid_t & pid)1381 bool AppMgrServiceInner::ProcessExist(pid_t &pid)
1382 {
1383     char pid_path[128] = {0};
1384     struct stat stat_buf;
1385     if (!pid) {
1386         return false;
1387     }
1388     if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) {
1389         return false;
1390     }
1391     if (stat(pid_path, &stat_buf) == 0) {
1392         return true;
1393     }
1394     return false;
1395 }
1396 
CheckAllProcessExist(std::list<pid_t> & pids)1397 bool AppMgrServiceInner::CheckAllProcessExist(std::list<pid_t> &pids)
1398 {
1399     for (auto iter = pids.begin(); iter != pids.end();) {
1400         if (!ProcessExist(*iter)) {
1401             iter = pids.erase(iter);
1402         } else {
1403             iter++;
1404         }
1405     }
1406     if (pids.empty()) {
1407         return true;
1408     }
1409     return false;
1410 }
1411 
SystemTimeMillisecond()1412 int64_t AppMgrServiceInner::SystemTimeMillisecond()
1413 {
1414     struct timespec t;
1415     t.tv_sec = 0;
1416     t.tv_nsec = 0;
1417     clock_gettime(CLOCK_MONOTONIC, &t);
1418     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
1419 }
1420 
GetAppRunningRecordByPid(const pid_t pid) const1421 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
1422 {
1423     if (!appRunningManager_) {
1424         HILOG_ERROR("appRunningManager nullptr!");
1425         return nullptr;
1426     }
1427     return appRunningManager_->GetAppRunningRecordByPid(pid);
1428 }
1429 
CreateAppRunningRecord(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const std::shared_ptr<ApplicationInfo> & appInfo,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::string & processName,const BundleInfo & bundleInfo,const HapModuleInfo & hapModuleInfo,const std::shared_ptr<AAFwk::Want> & want)1430 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(const sptr<IRemoteObject> &token,
1431     const sptr<IRemoteObject> &preToken, const std::shared_ptr<ApplicationInfo> &appInfo,
1432     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
1433     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1434 {
1435     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1436     if (!appRunningManager_) {
1437         HILOG_ERROR("appRunningManager nullptr!");
1438         return nullptr;
1439     }
1440     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
1441     if (!appRecord) {
1442         HILOG_ERROR("get app record failed");
1443         return nullptr;
1444     }
1445 
1446     appRecord->SetProcessAndExtensionType(abilityInfo);
1447     bool isKeepAlive = bundleInfo.isKeepAlive && bundleInfo.singleton;
1448     appRecord->SetKeepAliveAppState(isKeepAlive, false);
1449     appRecord->SetTaskHandler(taskHandler_);
1450     appRecord->SetEventHandler(eventHandler_);
1451     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1452     if (want) {
1453         appRecord->SetDebugApp(want->GetBoolParam(DEBUG_APP, false));
1454         appRecord->SetNativeDebug(want->GetBoolParam("nativeDebug", false));
1455         if (want->GetBoolParam(COLD_START, false)) {
1456             appRecord->SetDebugApp(true);
1457         }
1458         appRecord->SetPerfCmd(want->GetStringParam(PERF_CMD));
1459         appRecord->SetAppIndex(want->GetIntParam(DLP_PARAMS_INDEX, 0));
1460         appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
1461         appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0));
1462         appRecord->SetCallerPid(want->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
1463         appRecord->SetCallerUid(want->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
1464         appRecord->SetCallerTokenId(want->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
1465     }
1466 
1467     if (preToken) {
1468         auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1469         if (abilityRecord) {
1470             abilityRecord->SetPreToken(preToken);
1471         }
1472     }
1473 
1474     return appRecord;
1475 }
1476 
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag)1477 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag)
1478 {
1479     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1480     HILOG_DEBUG("Terminate ability come.");
1481     if (!token) {
1482         HILOG_ERROR("AppMgrServiceInner::TerminateAbility token is null!");
1483         return;
1484     }
1485     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1486     if (!appRecord) {
1487         HILOG_ERROR("AppMgrServiceInner::TerminateAbility app is not exist!");
1488         return;
1489     }
1490 
1491     if (appRunningManager_) {
1492         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner = shared_from_this();
1493         appRunningManager_->TerminateAbility(token, clearMissionFlag, appMgrServiceInner);
1494     }
1495 }
1496 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)1497 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
1498 {
1499     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1500     HILOG_DEBUG("state %{public}d.", static_cast<int32_t>(state));
1501     if (!token) {
1502         HILOG_ERROR("token is null!");
1503         return;
1504     }
1505 
1506     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1507     if (!appRecord) {
1508         HILOG_ERROR("app is not exist!");
1509         return;
1510     }
1511     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1512     if (!abilityRecord) {
1513         HILOG_ERROR("can not find ability record!");
1514         return;
1515     }
1516     if (state == abilityRecord->GetState()) {
1517         HILOG_ERROR("current state is already, no need update!");
1518         return;
1519     }
1520     if (abilityRecord->GetAbilityInfo() == nullptr) {
1521         HILOG_ERROR("ability info nullptr!");
1522         return;
1523     }
1524     auto type = abilityRecord->GetAbilityInfo()->type;
1525     if (type == AppExecFwk::AbilityType::SERVICE &&
1526         (state == AbilityState::ABILITY_STATE_CREATE ||
1527         state == AbilityState::ABILITY_STATE_TERMINATED ||
1528         state == AbilityState::ABILITY_STATE_CONNECTED ||
1529         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
1530         HILOG_INFO("StateChangedNotifyObserver service type, state:%{public}d", static_cast<int32_t>(state));
1531         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true, false);
1532         return;
1533     }
1534     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
1535         HILOG_ERROR("state is not foreground or background!");
1536         return;
1537     }
1538 
1539     appRecord->SetUpdateStateFromService(true);
1540     appRecord->UpdateAbilityState(token, state);
1541 }
1542 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)1543 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
1544 {
1545     if (!token) {
1546         HILOG_ERROR("token is null!");
1547         return;
1548     }
1549     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1550     if (!appRecord) {
1551         HILOG_ERROR("app is not exist!");
1552         return;
1553     }
1554     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1555     if (!abilityRecord) {
1556         HILOG_ERROR("can not find ability record!");
1557         return;
1558     }
1559     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false, false);
1560 }
1561 
OnStop()1562 void AppMgrServiceInner::OnStop()
1563 {
1564     if (!appRunningManager_) {
1565         HILOG_ERROR("appRunningManager nullptr!");
1566         return;
1567     }
1568 
1569     appRunningManager_->ClearAppRunningRecordMap();
1570     CloseAppSpawnConnection();
1571 }
1572 
OpenAppSpawnConnection()1573 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
1574 {
1575     if (remoteClientManager_ == nullptr) {
1576         HILOG_ERROR("remoteClientManager_ is null");
1577         return ERR_INVALID_VALUE;
1578     }
1579 
1580     if (remoteClientManager_->GetSpawnClient()) {
1581         return remoteClientManager_->GetSpawnClient()->OpenConnection();
1582     }
1583     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
1584 }
1585 
CloseAppSpawnConnection() const1586 void AppMgrServiceInner::CloseAppSpawnConnection() const
1587 {
1588     if (remoteClientManager_ == nullptr) {
1589         HILOG_ERROR("remoteClientManager_ is null");
1590         return;
1591     }
1592 
1593     if (remoteClientManager_->GetSpawnClient()) {
1594         remoteClientManager_->GetSpawnClient()->CloseConnection();
1595     }
1596 }
1597 
QueryAppSpawnConnectionState() const1598 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
1599 {
1600     if (remoteClientManager_ == nullptr) {
1601         HILOG_ERROR("remoteClientManager_ is null");
1602         return SpawnConnectionState::STATE_NOT_CONNECT;
1603     }
1604 
1605     if (remoteClientManager_->GetSpawnClient()) {
1606         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
1607     }
1608     return SpawnConnectionState::STATE_NOT_CONNECT;
1609 }
1610 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)1611 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
1612 {
1613     if (remoteClientManager_ == nullptr) {
1614         HILOG_ERROR("remoteClientManager_ is null");
1615         return;
1616     }
1617 
1618     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
1619 }
1620 
SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> & bundleMgrHelper)1621 void AppMgrServiceInner::SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> &bundleMgrHelper)
1622 {
1623     if (remoteClientManager_ == nullptr) {
1624         HILOG_ERROR("The remoteClientManager_ is nullptr.");
1625         return;
1626     }
1627 
1628     remoteClientManager_->SetBundleManagerHelper(bundleMgrHelper);
1629 }
1630 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)1631 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
1632 {
1633     pid_t callingPid = IPCSkeleton::GetCallingPid();
1634     pid_t pid = getpid();
1635     if (callingPid != pid) {
1636         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
1637         return;
1638     }
1639     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1640     if (callback != nullptr) {
1641         std::lock_guard lock(appStateCallbacksLock_);
1642         appStateCallbacks_.push_back(callback);
1643     }
1644 }
1645 
AbilityBehaviorAnalysis(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const int32_t visibility,const int32_t perceptibility,const int32_t connectionState)1646 void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1647     const int32_t visibility,       // 0:false,1:true
1648     const int32_t perceptibility,   // 0:false,1:true
1649     const int32_t connectionState)  // 0:false,1:true
1650 {
1651     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1652     if (!token) {
1653         HILOG_ERROR("token is null");
1654         return;
1655     }
1656     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1657     if (!appRecord) {
1658         HILOG_ERROR("app record is not exist for ability token");
1659         return;
1660     }
1661     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1662     if (!abilityRecord) {
1663         HILOG_ERROR("ability record is not exist for ability previous token");
1664         return;
1665     }
1666     if (preToken) {
1667         abilityRecord->SetPreToken(preToken);
1668     }
1669     abilityRecord->SetVisibility(visibility);
1670     abilityRecord->SetPerceptibility(perceptibility);
1671     abilityRecord->SetConnectionState(connectionState);
1672 }
1673 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)1674 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
1675 {
1676     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1677     if (!token) {
1678         HILOG_ERROR("token is null");
1679         return;
1680     }
1681     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1682     if (!appRecord) {
1683         HILOG_ERROR("app record is not exist for ability token");
1684         return;
1685     }
1686 
1687     // before exec ScheduleProcessSecurityExit return
1688     // The resident process won't let him die
1689     if (appRecord->IsKeepAliveApp()) {
1690         return;
1691     }
1692 
1693     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1694     if (pid > 0) {
1695         std::list<pid_t> pids;
1696         pids.push_back(pid);
1697         appRecord->ScheduleProcessSecurityExit();
1698         if (!WaitForRemoteProcessExit(pids, SystemTimeMillisecond())) {
1699             int32_t result = KillProcessByPid(pid);
1700             if (result < 0) {
1701                 HILOG_ERROR("KillProcessByAbilityToken kill process is fail");
1702                 return;
1703             }
1704         }
1705     }
1706 }
1707 
KillProcessesByUserId(int32_t userId)1708 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId)
1709 {
1710     if (!appRunningManager_) {
1711         HILOG_ERROR("appRunningManager_ is nullptr");
1712         return;
1713     }
1714 
1715     int64_t startTime = SystemTimeMillisecond();
1716     std::list<pid_t> pids;
1717     if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
1718         HILOG_INFO("The process corresponding to the userId did not start");
1719         return;
1720     }
1721     if (WaitForRemoteProcessExit(pids, startTime)) {
1722         HILOG_INFO("The remote process exited successfully ");
1723         return;
1724     }
1725     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1726         auto result = KillProcessByPid(*iter);
1727         if (result < 0) {
1728             HILOG_ERROR("KillProcessByPid is failed. pid: %{public}d", *iter);
1729             return;
1730         }
1731     }
1732 }
1733 
StartAbility(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<AppRunningRecord> & appRecord,const HapModuleInfo & hapModuleInfo,const std::shared_ptr<AAFwk::Want> & want)1734 void AppMgrServiceInner::StartAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1735     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<AppRunningRecord> &appRecord,
1736     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1737 {
1738     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1739     HILOG_DEBUG("start ability");
1740     if (!appRecord) {
1741         HILOG_ERROR("appRecord is null");
1742         return;
1743     }
1744 
1745     if (want) {
1746         want->SetParam(DLP_PARAMS_SECURITY_FLAG, appRecord->GetSecurityFlag());
1747 
1748         auto isDebugApp = want->GetBoolParam(DEBUG_APP, false);
1749         if (isDebugApp && !appRecord->IsDebugApp()) {
1750             ProcessAppDebug(appRecord, isDebugApp);
1751         }
1752     }
1753 
1754     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
1755     if (abilityInfo->launchMode == LaunchMode::SINGLETON && ability != nullptr) {
1756         HILOG_WARN("same ability info in singleton launch mode, will not add ability");
1757         return;
1758     }
1759 
1760     if (ability && preToken) {
1761         HILOG_ERROR("Ability is already started");
1762         ability->SetPreToken(preToken);
1763         return;
1764     }
1765 
1766     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
1767     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1768     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
1769     if (!moduleRecord) {
1770         HILOG_ERROR("add moduleRecord failed");
1771         return;
1772     }
1773 
1774     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
1775     if (!ability) {
1776         HILOG_ERROR("add ability failed");
1777         return;
1778     }
1779 
1780     if (preToken != nullptr) {
1781         ability->SetPreToken(preToken);
1782     }
1783 
1784     ApplicationState appState = appRecord->GetState();
1785     if (appState == ApplicationState::APP_STATE_CREATE) {
1786         HILOG_ERROR("in create state, don't launch ability");
1787         return;
1788     }
1789     appRecord->LaunchAbility(ability);
1790 }
1791 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const1792 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
1793     const sptr<IRemoteObject> &abilityToken) const
1794 {
1795     if (!appRunningManager_) {
1796         HILOG_ERROR("appRunningManager_ is nullptr");
1797         return nullptr;
1798     }
1799 
1800     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
1801 }
1802 
GetTerminatingAppRunningRecord(const sptr<IRemoteObject> & token) const1803 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetTerminatingAppRunningRecord(
1804     const sptr<IRemoteObject> &token) const
1805 {
1806     if (!appRunningManager_) {
1807         HILOG_ERROR("appRunningManager_ is nullptr.");
1808         return nullptr;
1809     }
1810     return appRunningManager_->GetTerminatingAppRunningRecord(token);
1811 }
1812 
AbilityTerminated(const sptr<IRemoteObject> & token)1813 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
1814 {
1815     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1816     HILOG_DEBUG("Terminate ability come.");
1817     if (!token) {
1818         HILOG_ERROR("Terminate ability error, token is null!");
1819         return;
1820     }
1821 
1822     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
1823     if (!appRecord) {
1824         HILOG_ERROR("Terminate ability error, appRecord is not exist!");
1825         return;
1826     }
1827 
1828     appRecord->AbilityTerminated(token);
1829 }
1830 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const1831 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
1832 {
1833     if (appRunningManager_ == nullptr) {
1834         HILOG_ERROR("appRunningManager is nullptr");
1835         return nullptr;
1836     }
1837     const auto&& appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
1838     const auto& iter = appRunningRecordMap.find(recordId);
1839     return iter != appRunningRecordMap.end() ? iter->second : nullptr;
1840 }
1841 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp,bool isFromWindowFocusChanged)1842 void AppMgrServiceInner::OnAppStateChanged(
1843     const std::shared_ptr<AppRunningRecord> &appRecord,
1844     const ApplicationState state,
1845     bool needNotifyApp,
1846     bool isFromWindowFocusChanged)
1847 {
1848     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1849     if (!appRecord) {
1850         HILOG_ERROR("OnAppStateChanged come, app record is null");
1851         return;
1852     }
1853 
1854     HILOG_DEBUG("OnAppStateChanged begin, bundleName is %{public}s, state:%{public}d",
1855         appRecord->GetBundleName().c_str(), static_cast<int32_t>(state));
1856     {
1857         std::lock_guard lock(appStateCallbacksLock_);
1858         for (const auto &callback : appStateCallbacks_) {
1859             if (callback != nullptr) {
1860                 callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
1861             }
1862         }
1863     }
1864 
1865     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStateChanged(
1866         appRecord, state, needNotifyApp, isFromWindowFocusChanged);
1867 }
1868 
OnAppStarted(const std::shared_ptr<AppRunningRecord> & appRecord)1869 void AppMgrServiceInner::OnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord)
1870 {
1871     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1872     if (!appRecord) {
1873         HILOG_ERROR("OnAppStarted come, app record is null");
1874         return;
1875     }
1876 
1877     if (appRecord->GetPriorityObject() == nullptr) {
1878         HILOG_ERROR("OnAppStarted come, appRecord's priorityobject is null");
1879         return;
1880     }
1881 
1882     HILOG_DEBUG("OnAppStarted begin, bundleName is %{public}s, pid:%{public}d",
1883         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
1884 
1885     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStarted(appRecord);
1886 }
1887 
1888 
OnAppStopped(const std::shared_ptr<AppRunningRecord> & appRecord)1889 void AppMgrServiceInner::OnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord)
1890 {
1891     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1892     if (!appRecord) {
1893         HILOG_ERROR("OnAppStopped come, app record is null");
1894         return;
1895     }
1896 
1897     if (appRecord->GetPriorityObject() == nullptr) {
1898         HILOG_ERROR("OnAppStarted come, appRecord's priorityObject is null");
1899         return;
1900     }
1901 
1902     HILOG_DEBUG("OnAppStopped begin, bundleName is %{public}s, pid:%{public}d",
1903         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
1904 
1905     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStopped(appRecord);
1906 }
1907 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1908 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
1909     const ApplicationState state)
1910 {
1911     AppProcessData processData;
1912     auto appInfoList = appRecord->GetAppInfoList();
1913     for (const auto &list : appInfoList) {
1914         AppData data;
1915         data.appName = list->name;
1916         data.uid = list->uid;
1917         processData.appDatas.push_back(data);
1918     }
1919     processData.processName = appRecord->GetProcessName();
1920     processData.pid = appRecord->GetPriorityObject()->GetPid();
1921     processData.appState = state;
1922     processData.isFocused = appRecord->GetFocusFlag();
1923     auto renderRecordMap = appRecord->GetRenderRecordMap();
1924     if (!renderRecordMap.empty()) {
1925         for (auto iter : renderRecordMap) {
1926             auto renderRecord = iter.second;
1927             if (renderRecord != nullptr) {
1928                 processData.renderPids.emplace_back(renderRecord->GetPid());
1929             }
1930         }
1931     }
1932     return processData;
1933 }
1934 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)1935 void AppMgrServiceInner::OnAbilityStateChanged(
1936     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
1937 {
1938     if (!ability) {
1939         HILOG_ERROR("ability is null");
1940         return;
1941     }
1942     std::lock_guard lock(appStateCallbacksLock_);
1943     for (const auto &callback : appStateCallbacks_) {
1944         if (callback != nullptr) {
1945             callback->OnAbilityRequestDone(ability->GetToken(), state);
1946         }
1947     }
1948 }
1949 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility,bool isFromWindowFocusChanged)1950 void AppMgrServiceInner::StateChangedNotifyObserver(
1951     const AbilityStateData abilityStateData, bool isAbility, bool isFromWindowFocusChanged)
1952 {
1953     DelayedSingleton<AppStateObserverManager>::GetInstance()->StateChangedNotifyObserver(
1954         abilityStateData, isAbility, isFromWindowFocusChanged);
1955 }
1956 
StartPerfProcess(const std::shared_ptr<AppRunningRecord> & appRecord,const std::string & perfCmd,const std::string & debugCmd,bool isSandboxApp) const1957 int32_t AppMgrServiceInner::StartPerfProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
1958     const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp) const
1959 {
1960     if (!remoteClientManager_->GetSpawnClient() || !appRecord) {
1961         HILOG_ERROR("appSpawnClient or appRecord is null");
1962         return ERR_INVALID_OPERATION;
1963     }
1964     if (perfCmd.empty() && debugCmd.empty()) {
1965         HILOG_DEBUG("perfCmd is empty");
1966         return ERR_INVALID_OPERATION;
1967     }
1968 
1969     auto&& startMsg = appRecord->GetStartMsg();
1970     startMsg.code = static_cast<int32_t>(AppSpawn::ClientSocket::AppOperateCode::SPAWN_NATIVE_PROCESS);
1971     if (!isSandboxApp) {
1972         HILOG_DEBUG("debuggablePipe sandbox: false.");
1973         startMsg.flags |= (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::NO_SANDBOX);
1974     } else {
1975         HILOG_INFO("debuggablePipe sandbox: true");
1976     }
1977     if (!perfCmd.empty()) {
1978         startMsg.renderParam = perfCmd;
1979         HILOG_INFO("debuggablePipe perfCmd:%{public}s", perfCmd.c_str());
1980     } else {
1981         startMsg.renderParam = debugCmd;
1982         HILOG_INFO("debuggablePipe debugCmd:%{public}s", debugCmd.c_str());
1983     }
1984     pid_t pid = 0;
1985     auto errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
1986     if (FAILED(errCode)) {
1987         HILOG_ERROR("failed to spawn new native process, errCode %{public}08x", errCode);
1988         return errCode;
1989     }
1990     return ERR_OK;
1991 }
1992 
SetOverlayInfo(const std::string & bundleName,const int32_t userId,AppSpawnStartMsg & startMsg)1993 void AppMgrServiceInner::SetOverlayInfo(const std::string &bundleName,
1994                                         const int32_t userId,
1995                                         AppSpawnStartMsg &startMsg)
1996 {
1997     if (remoteClientManager_ == nullptr) {
1998         HILOG_ERROR("The remoteClientManager_ is nullptr.");
1999         return;
2000     }
2001     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2002     if (bundleMgrHelper == nullptr) {
2003         HILOG_ERROR("The bundleMgrHelper is nullptr.");
2004         return;
2005     }
2006     auto overlayMgrProxy = bundleMgrHelper->GetOverlayManagerProxy();
2007     if (overlayMgrProxy !=  nullptr) {
2008         std::vector<OverlayModuleInfo> overlayModuleInfo;
2009         HILOG_DEBUG("Check overlay app begin.");
2010         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetOverlayModuleInfoForTarget");
2011         auto targetRet = IN_PROCESS_CALL(overlayMgrProxy->GetOverlayModuleInfoForTarget(
2012             bundleName, "", overlayModuleInfo, userId));
2013         if (targetRet == ERR_OK && overlayModuleInfo.size() != 0) {
2014             HILOG_DEBUG("Start an overlay app process.");
2015             startMsg.flags = startMsg.flags | APP_OVERLAY_FLAG;
2016             std::string overlayInfoPaths;
2017             for (auto it : overlayModuleInfo) {
2018                 overlayInfoPaths += (it.hapPath + "|");
2019             }
2020             startMsg.overlayInfo = overlayInfoPaths;
2021         }
2022     }
2023 }
2024 
StartProcessVerifyPermission(const BundleInfo & bundleInfo,bool & hasAccessBundleDirReq,uint8_t & setAllowInternet,uint8_t & allowInternet,std::vector<int32_t> & gids,std::set<std::string> & permissions)2025 void AppMgrServiceInner::StartProcessVerifyPermission(const BundleInfo &bundleInfo, bool &hasAccessBundleDirReq,
2026                                                       uint8_t &setAllowInternet, uint8_t &allowInternet,
2027                                                       std::vector<int32_t> &gids, std::set<std::string> &permissions)
2028 {
2029     hasAccessBundleDirReq = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
2030         [] (const auto &reqPermission) {
2031             if (PERMISSION_ACCESS_BUNDLE_DIR == reqPermission) {
2032                 return true;
2033             }
2034             return false;
2035         });
2036 
2037     auto token = bundleInfo.applicationInfo.accessTokenId;
2038     {
2039         HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::VerifyAccessToken");
2040         int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_INTERNET, false);
2041         if (result != Security::AccessToken::PERMISSION_GRANTED) {
2042             setAllowInternet = 1;
2043             allowInternet = 0;
2044     #ifdef APP_MGR_SERVICE_APPMS
2045             auto ret = OHOS::NetManagerStandard::NetConnClient::GetInstance().SetInternetPermission(bundleInfo.uid, 0);
2046             HILOG_DEBUG("SetInternetPermission, ret = %{public}d", ret);
2047         } else {
2048             auto ret = OHOS::NetManagerStandard::NetConnClient::GetInstance().SetInternetPermission(bundleInfo.uid, 1);
2049             HILOG_DEBUG("SetInternetPermission, ret = %{public}d", ret);
2050             gids.push_back(NETSYS_SOCKET_GROUPID);
2051     #endif
2052         }
2053 
2054         result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_MANAGE_VPN, false);
2055         if (result == Security::AccessToken::PERMISSION_GRANTED) {
2056             gids.push_back(BLUETOOTH_GROUPID);
2057         }
2058 
2059         if (hasAccessBundleDirReq) {
2060             int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token,
2061                 PERMISSION_ACCESS_BUNDLE_DIR, false);
2062             if (result != Security::AccessToken::PERMISSION_GRANTED) {
2063                 HILOG_ERROR("StartProcess PERMISSION_ACCESS_BUNDLE_DIR NOT GRANTED");
2064                 hasAccessBundleDirReq = false;
2065             }
2066         }
2067     }
2068 
2069     std::set<std::string> mountPermissionList = AppSpawn::AppspawnMountPermission::GetMountPermissionList();
2070     for (std::string permission : mountPermissionList) {
2071         if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, permission, false) ==
2072             Security::AccessToken::PERMISSION_GRANTED) {
2073             permissions.insert(permission);
2074         }
2075     }
2076 }
2077 
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)2078 void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags,
2079     std::shared_ptr<AppRunningRecord> appRecord, const int uid, const BundleInfo &bundleInfo,
2080     const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag)
2081 {
2082     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2083     HILOG_DEBUG("StartProcess: %{public}s", bundleName.c_str());
2084     if (!appRecord) {
2085         HILOG_ERROR("appRecord is null");
2086         return;
2087     }
2088 
2089     if (!remoteClientManager_->GetSpawnClient()) {
2090         HILOG_ERROR("appSpawnClient is null");
2091         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2092         return;
2093     }
2094 
2095     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2096     if (bundleMgrHelper == nullptr) {
2097         HILOG_ERROR("Get bundle manager helper fail.");
2098         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2099         return;
2100     }
2101 
2102     auto userId = GetUserIdByUid(uid);
2103     HspList hspList;
2104     ErrCode ret = bundleMgrHelper->GetBaseSharedBundleInfos(bundleName, hspList,
2105         AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
2106     if (ret != ERR_OK) {
2107         HILOG_ERROR("GetBaseSharedBundleInfos failed: %{public}d", ret);
2108         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2109         return;
2110     }
2111 
2112     DataGroupInfoList dataGroupInfoList;
2113     bool result = bundleMgrHelper->QueryDataGroupInfos(bundleName, userId, dataGroupInfoList);
2114     if (!result || dataGroupInfoList.empty()) {
2115         HILOG_DEBUG("the bundle has no groupInfos");
2116     }
2117 
2118     bool hasAccessBundleDirReq;
2119     uint8_t setAllowInternet = 0;
2120     uint8_t allowInternet = 1;
2121     std::vector<int32_t> gids;
2122     std::set<std::string> permissions;
2123     StartProcessVerifyPermission(bundleInfo, hasAccessBundleDirReq, setAllowInternet, allowInternet, gids,
2124                                  permissions);
2125 
2126     AppSpawnStartMsg startMsg;
2127     startMsg.uid = bundleInfo.uid;
2128     startMsg.gid = bundleInfo.gid;
2129     startMsg.gids = gids;
2130     startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId;
2131     startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel;
2132     startMsg.bundleName = bundleName;
2133     startMsg.renderParam = RENDER_PARAM;
2134     startMsg.flags = startFlags;
2135     startMsg.bundleIndex = bundleIndex;
2136     startMsg.setAllowInternet = setAllowInternet;
2137     startMsg.allowInternet = allowInternet;
2138     startMsg.hspList = hspList;
2139     startMsg.dataGroupInfoList = dataGroupInfoList;
2140     startMsg.hapFlags = bundleInfo.isPreInstallApp ? 1 : 0;
2141 
2142     startMsg.mountPermissionFlags = AppSpawn::AppspawnMountPermission::GenPermissionCode(permissions);
2143     startMsg.ownerId = bundleInfo.signatureInfo.appIdentifier;
2144     if (hasAccessBundleDirReq) {
2145         startMsg.flags = startMsg.flags | APP_ACCESS_BUNDLE_DIR;
2146     }
2147 
2148     if (VerifyPermission(bundleInfo, PERMISSION_GET_BUNDLE_RESOURCES)) {
2149         startMsg.flags = startMsg.flags | GET_BUNDLE_RESOURCES_FLAG;
2150     }
2151 
2152     SetOverlayInfo(bundleName, userId, startMsg);
2153 
2154     HILOG_INFO("apl is %{public}s, bundleName is %{public}s, startFlags is %{public}d.",
2155         startMsg.apl.c_str(), bundleName.c_str(), startFlags);
2156 
2157     bool bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleGidsByUid(bundleName, uid, startMsg.gids));
2158     if (!bundleMgrResult) {
2159         HILOG_ERROR("GetBundleGids is fail.");
2160         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2161         return;
2162     }
2163 
2164     startMsg.procName = processName;
2165     startMsg.accessTokenIdEx = bundleInfo.applicationInfo.accessTokenIdEx;
2166 
2167     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
2168     pid_t pid = 0;
2169     HILOG_DEBUG("bundleName: %{public}s.", bundleName.c_str());
2170     ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
2171     if (FAILED(errCode)) {
2172         HILOG_ERROR("failed to spawn new app process, errCode %{public}08x", errCode);
2173         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2174         return;
2175     }
2176     HILOG_DEBUG("pid: %{public}d, processName: %{public}s.",
2177         pid, processName.c_str());
2178     SetRunningSharedBundleList(bundleName, hspList);
2179     appRecord->GetPriorityObject()->SetPid(pid);
2180     appRecord->SetUid(startMsg.uid);
2181     appRecord->SetStartMsg(startMsg);
2182     appRecord->SetAppMgrServiceInner(weak_from_this());
2183     appRecord->SetSpawned();
2184     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false, false);
2185     AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
2186     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessCreated(appRecord);
2187     if (!appExistFlag) {
2188         OnAppStarted(appRecord);
2189     }
2190     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
2191     SendProcessStartEvent(appRecord);
2192     ProcessAppDebug(appRecord, appRecord->IsDebugApp());
2193 }
2194 
MakeAppDebugInfo(const std::shared_ptr<AppRunningRecord> & appRecord,const bool & isDebugStart)2195 AppDebugInfo AppMgrServiceInner::MakeAppDebugInfo(
2196     const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart)
2197 {
2198     AppDebugInfo info;
2199     if (appRecord == nullptr) {
2200         HILOG_ERROR("appRecord is nullptr.");
2201         return info;
2202     }
2203 
2204     info.bundleName = appRecord->GetBundleName();
2205     auto priorityObject = appRecord->GetPriorityObject();
2206     if (priorityObject) {
2207         info.pid = priorityObject->GetPid();
2208     }
2209     info.uid = appRecord->GetUid();
2210     info.isDebugStart = isDebugStart;
2211     return info;
2212 }
2213 
ProcessAppDebug(const std::shared_ptr<AppRunningRecord> & appRecord,const bool & isDebugStart)2214 void AppMgrServiceInner::ProcessAppDebug(const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart)
2215 {
2216     HILOG_DEBUG("Called.");
2217     if (appRecord == nullptr || appDebugManager_ == nullptr) {
2218         HILOG_ERROR("appRecord or appDebugManager_ is nullptr.");
2219         return;
2220     }
2221 
2222     auto startDebug = [this, appRecord](const bool &isDebugStart) {
2223         std::vector<AppDebugInfo> debugInfos;
2224         debugInfos.emplace_back(MakeAppDebugInfo(appRecord, isDebugStart));
2225         appDebugManager_->StartDebug(debugInfos);
2226     };
2227 
2228     if (isDebugStart && !appRecord->IsDebugApp()) {
2229         appRecord->SetDebugApp(true);
2230         startDebug(true);
2231         return;
2232     }
2233 
2234     if (appRecord->IsDebugApp()) {
2235         startDebug(true);
2236         return;
2237     }
2238 
2239     auto bundleName = appRecord->GetBundleName();
2240     if (appDebugManager_->IsAttachDebug(bundleName)) {
2241         appRecord->SetAttachDebug(true);
2242         startDebug(false);
2243     }
2244 }
2245 
UpDateStartupType(const std::shared_ptr<AbilityInfo> & info,int32_t & abilityType,int32_t & extensionType)2246 void AppMgrServiceInner::UpDateStartupType(
2247     const std::shared_ptr<AbilityInfo> &info, int32_t &abilityType, int32_t &extensionType)
2248 {
2249     if (info == nullptr) {
2250         return;
2251     }
2252 
2253     HILOG_DEBUG("bundleName:%{public}s, abilityName:%{public}s", info->bundleName.c_str(), info->name.c_str());
2254     abilityType = static_cast<int32_t>(info->type);
2255     if (info->type != AbilityType::EXTENSION) {
2256         return;
2257     }
2258 
2259     extensionType = static_cast<int32_t>(info->extensionAbilityType);
2260 }
2261 
SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> & appRecord)2262 bool AppMgrServiceInner::SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
2263 {
2264     if (!appRecord) {
2265         HILOG_ERROR("appRecord is nullptr");
2266         return false;
2267     }
2268 
2269     AAFwk::EventInfo eventInfo;
2270     time_t currentTime;
2271     time(&currentTime);
2272     eventInfo.time = currentTime;
2273     eventInfo.callerUid = appRecord->GetCallerUid() == -1 ? IPCSkeleton::GetCallingUid() : appRecord->GetCallerUid();
2274     if (!appRecord->GetAbilities().empty()) {
2275         auto abilityinfo = appRecord->GetAbilities().begin()->second->GetAbilityInfo();
2276         UpDateStartupType(abilityinfo, eventInfo.abilityType, eventInfo.extensionType);
2277     } else {
2278         HILOG_INFO("Abilities nullptr!");
2279     }
2280 
2281     auto callerAppRecord = GetAppRunningRecordByPid(appRecord->GetCallerPid());
2282     if (callerAppRecord == nullptr) {
2283         Security::AccessToken::NativeTokenInfo nativeTokenInfo = {};
2284         auto token = appRecord->GetCallerTokenId() == -1 ?
2285             static_cast<int>(IPCSkeleton::GetCallingTokenID()) : appRecord->GetCallerTokenId();
2286         Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(token, nativeTokenInfo);
2287         eventInfo.callerBundleName = "";
2288         eventInfo.callerProcessName = nativeTokenInfo.processName;
2289     } else {
2290         if (callerAppRecord->GetBundleName().empty()) {
2291             eventInfo.callerBundleName = callerAppRecord->GetName();
2292         } else {
2293             eventInfo.callerBundleName = callerAppRecord->GetBundleName();
2294         }
2295         eventInfo.callerProcessName = callerAppRecord->GetProcessName();
2296     }
2297     if (!appRecord->GetBundleName().empty()) {
2298         eventInfo.bundleName = appRecord->GetBundleName();
2299     }
2300     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::PROCESS_START, HiSysEventType::BEHAVIOR, eventInfo);
2301     HILOG_DEBUG("%{public}s. time : %{public}" PRId64 ", abilityType : %{public}d, bundle : %{public}s,\
2302         uid : %{public}d, process : %{public}s",
2303         __func__, eventInfo.time, eventInfo.abilityType, eventInfo.callerBundleName.c_str(), eventInfo.callerUid,
2304         eventInfo.callerProcessName.c_str());
2305     SendReStartProcessEvent(eventInfo, appRecord);
2306 
2307     return true;
2308 }
2309 
SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AbilityInfo> & abilityInfo,const AppStartType startType)2310 void AppMgrServiceInner::SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
2311     const std::shared_ptr<AbilityInfo> &abilityInfo, const AppStartType startType)
2312 {
2313     if (!appRecord) {
2314         HILOG_ERROR("appRecord is nullptr");
2315         return;
2316     }
2317     AAFwk::EventInfo eventInfo;
2318     auto applicationInfo = appRecord->GetApplicationInfo();
2319     if (!applicationInfo) {
2320         HILOG_ERROR("applicationInfo is nullptr, can not get app information");
2321     } else {
2322         eventInfo.bundleName = applicationInfo->name;
2323         eventInfo.versionName = applicationInfo->versionName;
2324         eventInfo.versionCode = applicationInfo->versionCode;
2325     }
2326     if (!abilityInfo) {
2327         HILOG_ERROR("abilityInfo is nullptr, can not get ability information");
2328     } else {
2329         eventInfo.abilityName = abilityInfo->name;
2330     }
2331     if (appRecord->GetPriorityObject() == nullptr) {
2332         HILOG_ERROR("appRecord's priorityObject is null");
2333     } else {
2334         eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
2335     }
2336     eventInfo.startType = static_cast<int32_t>(startType);
2337     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
2338 }
2339 
RemoveAppFromRecentList(const std::string & appName,const std::string & processName)2340 void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, const std::string &processName)
2341 {
2342     int64_t startTime = 0;
2343     std::list<pid_t> pids;
2344     auto appTaskInfo = appProcessManager_->GetAppTaskInfoByProcessName(appName, processName);
2345     if (!appTaskInfo) {
2346         return;
2347     }
2348     auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
2349     if (!appRecord) {
2350         appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
2351         return;
2352     }
2353 
2354     // Do not delete resident processes, before exec ScheduleProcessSecurityExit
2355     if (appRecord->IsKeepAliveApp()) {
2356         return;
2357     }
2358 
2359     startTime = SystemTimeMillisecond();
2360     pids.push_back(appTaskInfo->GetPid());
2361     appRecord->ScheduleProcessSecurityExit();
2362     if (!WaitForRemoteProcessExit(pids, startTime)) {
2363         int32_t result = KillProcessByPid(appTaskInfo->GetPid());
2364         if (result < 0) {
2365             HILOG_ERROR("RemoveAppFromRecentList kill process is fail");
2366             return;
2367         }
2368     }
2369     appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
2370 }
2371 
GetRecentAppList() const2372 const std::list<const std::shared_ptr<AppTaskInfo>> &AppMgrServiceInner::GetRecentAppList() const
2373 {
2374     return appProcessManager_->GetRecentAppList();
2375 }
2376 
ClearRecentAppList()2377 void AppMgrServiceInner::ClearRecentAppList()
2378 {
2379     int64_t startTime = 0;
2380     std::list<pid_t> pids;
2381     if (GetAllPids(pids)) {
2382         return;
2383     }
2384 
2385     startTime = SystemTimeMillisecond();
2386     if (WaitForRemoteProcessExit(pids, startTime)) {
2387         appProcessManager_->ClearRecentAppList();
2388         return;
2389     }
2390     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
2391         int32_t result = KillProcessByPid(*iter);
2392         if (result < 0) {
2393             HILOG_ERROR("ClearRecentAppList kill process is fail");
2394             return;
2395         }
2396     }
2397     appProcessManager_->ClearRecentAppList();
2398 }
2399 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess,bool isChildProcess)2400 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess, bool isChildProcess)
2401 {
2402     HILOG_ERROR("On remote died.");
2403     if (isRenderProcess) {
2404         OnRenderRemoteDied(remote);
2405         return;
2406     }
2407     if (isChildProcess) {
2408         OnChildProcessRemoteDied(remote);
2409         return;
2410     }
2411 
2412     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
2413     {
2414         std::lock_guard lock(exceptionLock_);
2415         appRecord = appRunningManager_->OnRemoteDied(remote);
2416     }
2417     if (appRecord == nullptr) {
2418         HILOG_INFO("app record is not exist.");
2419         return;
2420     }
2421 
2422     ClearData(appRecord);
2423 }
2424 
ClearAppRunningData(const std::shared_ptr<AppRunningRecord> & appRecord,bool containsApp)2425 void AppMgrServiceInner::ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord, bool containsApp)
2426 {
2427     if (!appRecord) {
2428         return;
2429     }
2430 
2431     if (containsApp) {
2432         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2433     }
2434 
2435     FinishUserTestLocked("App died", -1, appRecord);
2436     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_REMOTE_DIED);
2437 
2438     for (const auto &item : appRecord->GetAbilities()) {
2439         const auto &abilityRecord = item.second;
2440         appRecord->StateChangedNotifyObserver(abilityRecord,
2441             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true, false);
2442     }
2443     RemoveAppFromRecentListById(appRecord->GetRecordId());
2444     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
2445 
2446     // kill render if exist.
2447     KillRenderProcess(appRecord);
2448     KillChildProcess(appRecord);
2449 
2450     if (appRecord->GetPriorityObject() != nullptr) {
2451         SendProcessExitEvent(appRecord->GetPriorityObject()->GetPid());
2452     }
2453 
2454     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
2455         OnAppStopped(appRecord);
2456     }
2457 
2458     if (appDebugManager_ != nullptr) {
2459         auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
2460         appDebugManager_->RemoveAppDebugInfo(info);
2461     }
2462 
2463     ClearAppRunningDataForKeepAlive(appRecord);
2464 
2465     auto uid = appRecord->GetUid();
2466     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
2467 }
2468 
PushAppFront(const int32_t recordId)2469 void AppMgrServiceInner::PushAppFront(const int32_t recordId)
2470 {
2471     appProcessManager_->PushAppFront(recordId);
2472 }
2473 
RemoveAppFromRecentListById(const int32_t recordId)2474 void AppMgrServiceInner::RemoveAppFromRecentListById(const int32_t recordId)
2475 {
2476     appProcessManager_->RemoveAppFromRecentListById(recordId);
2477 }
2478 
AddAppToRecentList(const std::string & appName,const std::string & processName,const pid_t pid,const int32_t recordId)2479 void AppMgrServiceInner::AddAppToRecentList(
2480     const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId)
2481 {
2482     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2483     appProcessManager_->AddAppToRecentList(appName, processName, pid, recordId);
2484 }
2485 
GetAppTaskInfoById(const int32_t recordId) const2486 const std::shared_ptr<AppTaskInfo> AppMgrServiceInner::GetAppTaskInfoById(const int32_t recordId) const
2487 {
2488     return appProcessManager_->GetAppTaskInfoById(recordId);
2489 }
2490 
HandleTimeOut(const AAFwk::EventWrap & event)2491 void AppMgrServiceInner::HandleTimeOut(const AAFwk::EventWrap &event)
2492 {
2493     HILOG_DEBUG("called");
2494     if (!appRunningManager_) {
2495         HILOG_ERROR("appRunningManager is nullptr");
2496         return;
2497     }
2498 
2499     // check libc.hook_mode
2500     const int bufferLen = 128;
2501     char paramOutBuf[bufferLen] = {0};
2502     const char *hook_mode = "startup:";
2503     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
2504     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
2505         HILOG_DEBUG("HandleTimeOut, Hook_mode: no handle time out");
2506         return;
2507     }
2508 
2509     switch (event.GetEventId()) {
2510         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
2511             appRunningManager_->HandleTerminateTimeOut(event.GetParam());
2512             break;
2513         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
2514             SendHiSysEvent(event.GetEventId(), event.GetParam());
2515             HandleTerminateApplicationTimeOut(event.GetParam());
2516             break;
2517         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
2518             SendHiSysEvent(event.GetEventId(), event.GetParam());
2519             HandleStartSpecifiedProcessTimeout(event.GetParam());
2520             break;
2521         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
2522         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
2523             SendHiSysEvent(event.GetEventId(), event.GetParam());
2524             HandleAddAbilityStageTimeOut(event.GetParam());
2525             break;
2526         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
2527             SendHiSysEvent(event.GetEventId(), event.GetParam());
2528             HandleStartSpecifiedAbilityTimeOut(event.GetParam());
2529             break;
2530         default:
2531             break;
2532     }
2533 }
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)2534 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
2535 {
2536     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2537     HILOG_DEBUG("called");
2538     if (!appRunningManager_) {
2539         HILOG_ERROR("appRunningManager_ is nullptr");
2540         return;
2541     }
2542     appRunningManager_->HandleAbilityAttachTimeOut(token);
2543 }
2544 
PrepareTerminate(const sptr<IRemoteObject> & token)2545 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token)
2546 {
2547     HILOG_DEBUG("called");
2548     if (!appRunningManager_) {
2549         HILOG_ERROR("appRunningManager_ is nullptr");
2550         return;
2551     }
2552     appRunningManager_->PrepareTerminate(token);
2553 }
2554 
HandleTerminateApplicationTimeOut(const int64_t eventId)2555 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId)
2556 {
2557     HILOG_DEBUG("called");
2558     if (!appRunningManager_) {
2559         HILOG_ERROR("appRunningManager_ is nullptr");
2560         return;
2561     }
2562     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2563     TerminateApplication(appRecord);
2564 }
2565 
TerminateApplication(const std::shared_ptr<AppRunningRecord> & appRecord)2566 void AppMgrServiceInner::TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
2567 {
2568     if (!appRecord) {
2569         HILOG_ERROR("appRecord is nullptr");
2570         return;
2571     }
2572     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
2573     appRecord->RemoveAppDeathRecipient();
2574     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT);
2575     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false);
2576     pid_t pid = appRecord->GetPriorityObject()->GetPid();
2577     if (pid > 0) {
2578         auto timeoutTask = [pid, innerService = shared_from_this()]() {
2579             HILOG_INFO("KillProcessByPid %{public}d", pid);
2580             int32_t result = innerService->KillProcessByPid(pid);
2581             innerService->SendProcessExitEvent(pid);
2582             if (result < 0) {
2583                 HILOG_ERROR("KillProcessByPid kill process is fail");
2584                 return;
2585             }
2586         };
2587         if (!taskHandler_) {
2588             HILOG_ERROR("taskHandler_ is nullptr");
2589             return;
2590         }
2591         taskHandler_->SubmitTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
2592     }
2593     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2594     RemoveAppFromRecentListById(appRecord->GetRecordId());
2595     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
2596         RemoveRunningSharedBundleList(appRecord->GetBundleName());
2597     }
2598     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
2599     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
2600         OnAppStopped(appRecord);
2601     }
2602 
2603     if (appDebugManager_) {
2604         auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
2605         appDebugManager_->RemoveAppDebugInfo(info);
2606     }
2607 
2608     auto uid = appRecord->GetUid();
2609     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
2610 }
2611 
HandleAddAbilityStageTimeOut(const int64_t eventId)2612 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId)
2613 {
2614     HILOG_DEBUG("called");
2615     if (!appRunningManager_) {
2616         HILOG_ERROR("appRunningManager_ is nullptr");
2617         return;
2618     }
2619     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2620     if (!appRecord) {
2621         HILOG_ERROR("appRecord is nullptr");
2622         return;
2623     }
2624 
2625     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
2626         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
2627     }
2628 
2629     if (appRecord->IsNewProcessRequest() && startSpecifiedAbilityResponse_) {
2630         startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant());
2631     }
2632 
2633     KillApplicationByRecord(appRecord);
2634 }
2635 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)2636 void AppMgrServiceInner::GetRunningProcessInfoByToken(
2637     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
2638 {
2639     HILOG_DEBUG("called");
2640     if (!CheckGetRunningInfoPermission()) {
2641         return;
2642     }
2643 
2644     appRunningManager_->GetRunningProcessInfoByToken(token, info);
2645 }
2646 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info) const2647 void AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const
2648 {
2649     HILOG_DEBUG("called");
2650     if (!CheckGetRunningInfoPermission()) {
2651         return;
2652     }
2653 
2654     appRunningManager_->GetRunningProcessInfoByPid(pid, info);
2655 }
2656 
SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const2657 void AppMgrServiceInner::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const
2658 {
2659     HILOG_DEBUG("called");
2660     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2661         return;
2662     }
2663 
2664     appRunningManager_->SetAbilityForegroundingFlagToAppRecord(pid);
2665 }
2666 
CheckGetRunningInfoPermission() const2667 bool AppMgrServiceInner::CheckGetRunningInfoPermission() const
2668 {
2669     if (!appRunningManager_) {
2670         HILOG_ERROR("appRunningManager_ is nullptr");
2671         return false;
2672     }
2673 
2674     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2675     if (!isPerm) {
2676         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2677         return false;
2678     }
2679 
2680     return true;
2681 }
2682 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)2683 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
2684 {
2685     HILOG_INFO("%{public}s called", __func__);
2686 
2687     HILOG_INFO("bundle info size: [%{public}zu]", infos.size());
2688     StartResidentProcess(infos, -1, true);
2689 }
2690 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount,bool isEmptyKeepAliveApp)2691 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount,
2692     bool isEmptyKeepAliveApp)
2693 {
2694     HILOG_INFO("start resident process");
2695     if (infos.empty()) {
2696         HILOG_ERROR("infos is empty!");
2697         return;
2698     }
2699 
2700     if (!appRunningManager_) {
2701         HILOG_ERROR("appRunningManager_ is nullptr");
2702         return;
2703     }
2704 
2705     for (auto &bundle : infos) {
2706         HILOG_INFO("processName = [%{public}s]", bundle.applicationInfo.process.c_str());
2707         if (bundle.applicationInfo.process.empty()) {
2708             continue;
2709         }
2710         auto processName = bundle.applicationInfo.process;
2711         // Inspection records
2712         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
2713             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
2714         if (appRecord) {
2715             HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
2716             continue;
2717         }
2718         HILOG_INFO("Start empty resident process, processName = [%{public}s]", processName.c_str());
2719         StartEmptyResidentProcess(bundle, processName, restartCount, isEmptyKeepAliveApp);
2720     }
2721 }
2722 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount,bool isEmptyKeepAliveApp)2723 void AppMgrServiceInner::StartEmptyResidentProcess(
2724     const BundleInfo &info, const std::string &processName, int restartCount, bool isEmptyKeepAliveApp)
2725 {
2726     HILOG_INFO("start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
2727     if (!CheckRemoteClient() || !appRunningManager_) {
2728         HILOG_INFO("Failed to start resident process!");
2729         return;
2730     }
2731 
2732     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name);
2733     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
2734 
2735     if (!appExistFlag) {
2736         NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
2737     }
2738 
2739     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
2740     if (!appRecord) {
2741         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2742         return;
2743     }
2744 
2745     appRecord->SetKeepAliveAppState(true, isEmptyKeepAliveApp);
2746 
2747     StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, info, appInfo->bundleName, 0, appExistFlag);
2748 
2749     // If it is empty, the startup failed
2750     if (!appRecord) {
2751         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2752         return;
2753     }
2754 
2755     if (restartCount > 0) {
2756         HILOG_INFO("StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount);
2757         appRecord->SetRestartResidentProcCount(restartCount);
2758     }
2759 
2760     appRecord->SetTaskHandler(taskHandler_);
2761     appRecord->SetEventHandler(eventHandler_);
2762     appRecord->AddModules(appInfo, info.hapModuleInfos);
2763     HILOG_INFO("StartEmptyResidentProcess of pid : [%{public}d], ", appRecord->GetPriorityObject()->GetPid());
2764 }
2765 
CheckRemoteClient()2766 bool AppMgrServiceInner::CheckRemoteClient()
2767 {
2768     if (!remoteClientManager_) {
2769         HILOG_ERROR("remoteClientManager_ is null");
2770         return false;
2771     }
2772 
2773     if (!remoteClientManager_->GetSpawnClient()) {
2774         HILOG_ERROR("appSpawnClient is null");
2775         return false;
2776     }
2777 
2778     if (!remoteClientManager_->GetBundleManagerHelper()) {
2779         HILOG_ERROR("Get bundle manager helper fail.");
2780         return false;
2781     }
2782     return true;
2783 }
2784 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)2785 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
2786 {
2787     if (appRecord == nullptr) {
2788         HILOG_ERROR("Restart resident process failed, the appRecord is nullptr.");
2789         return;
2790     }
2791     struct timespec t;
2792     t.tv_sec = 0;
2793     t.tv_nsec = 0;
2794     clock_gettime(CLOCK_MONOTONIC, &t);
2795     appRecord->SetRestartTimeMillis(static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS));
2796     appRecord->DecRestartResidentProcCount();
2797 
2798     auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
2799         return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
2800     };
2801     auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(), findRestartResidentTask);
2802     if (findIter != restartResedentTaskList_.end()) {
2803         restartResedentTaskList_.erase(findIter);
2804     }
2805 
2806     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
2807         HILOG_ERROR("restart resident process failed!");
2808         return;
2809     }
2810 
2811     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2812     BundleInfo bundleInfo;
2813     auto callerUid = IPCSkeleton::GetCallingUid();
2814     auto userId = GetUserIdByUid(callerUid);
2815     if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(
2816         appRecord->GetBundleName(), BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
2817         HILOG_ERROR("GetBundleInfo fail.");
2818         return;
2819     }
2820     std::vector<BundleInfo> infos;
2821     infos.emplace_back(bundleInfo);
2822     HILOG_INFO("the resident process [%{public}s] remaining restarts num is [%{public}d]",
2823         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
2824     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount(), appRecord->IsEmptyKeepAliveApp());
2825 }
2826 
NotifyAppStatus(const std::string & bundleName,const std::string & eventData)2827 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData)
2828 {
2829     HILOG_DEBUG("bundle name is %{public}s, event is %{public}s",
2830         bundleName.c_str(), eventData.c_str());
2831     Want want;
2832     want.SetAction(eventData);
2833     ElementName element;
2834     element.SetBundleName(bundleName);
2835     want.SetElement(element);
2836     want.SetParam(Constants::USER_ID, 0);
2837     EventFwk::CommonEventData commonData {want};
2838     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
2839 }
2840 
NotifyAppStatusByCallerUid(const std::string & bundleName,const int32_t userId,const int32_t callerUid,const std::string & eventData)2841 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t userId,
2842     const int32_t callerUid, const std::string &eventData)
2843 {
2844     HILOG_INFO("%{public}s called, bundle name is %{public}s, , userId is %{public}d, event is %{public}s",
2845         __func__, bundleName.c_str(), userId, eventData.c_str());
2846     Want want;
2847     want.SetAction(eventData);
2848     ElementName element;
2849     element.SetBundleName(bundleName);
2850     want.SetElement(element);
2851     want.SetParam(Constants::USER_ID, userId);
2852     want.SetParam(Constants::UID, callerUid);
2853     EventFwk::CommonEventData commonData {want};
2854     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
2855 }
2856 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)2857 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(
2858     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
2859 {
2860     CHECK_CALLER_IS_SYSTEM_APP;
2861     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterApplicationStateObserver(
2862         observer, bundleNameList);
2863 }
2864 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)2865 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
2866 {
2867     CHECK_CALLER_IS_SYSTEM_APP;
2868     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterApplicationStateObserver(observer);
2869 }
2870 
RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)2871 int32_t AppMgrServiceInner::RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
2872 {
2873     CHECK_CALLER_IS_SYSTEM_APP;
2874     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterAppForegroundStateObserver(observer);
2875 }
2876 
UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)2877 int32_t AppMgrServiceInner::UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
2878 {
2879     CHECK_CALLER_IS_SYSTEM_APP;
2880     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterAppForegroundStateObserver(observer);
2881 }
2882 
RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)2883 int32_t AppMgrServiceInner::RegisterAbilityForegroundStateObserver(
2884     const sptr<IAbilityForegroundStateObserver> &observer)
2885 {
2886     CHECK_CALLER_IS_SYSTEM_APP;
2887     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterAbilityForegroundStateObserver(observer);
2888 }
2889 
UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)2890 int32_t AppMgrServiceInner::UnregisterAbilityForegroundStateObserver(
2891     const sptr<IAbilityForegroundStateObserver> &observer)
2892 {
2893     CHECK_CALLER_IS_SYSTEM_APP;
2894     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterAbilityForegroundStateObserver(observer);
2895 }
2896 
GetForegroundApplications(std::vector<AppStateData> & list)2897 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
2898 {
2899     HILOG_DEBUG("begin.");
2900     CHECK_CALLER_IS_SYSTEM_APP;
2901     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2902     if (!isPerm) {
2903         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2904         return ERR_PERMISSION_DENIED;
2905     }
2906 
2907     appRunningManager_->GetForegroundApplications(list);
2908     return ERR_OK;
2909 }
2910 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)2911 int AppMgrServiceInner::StartUserTestProcess(
2912     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
2913 {
2914     HILOG_INFO("Enter");
2915     if (!observer) {
2916         HILOG_ERROR("observer nullptr.");
2917         return ERR_INVALID_VALUE;
2918     }
2919     if (!appRunningManager_) {
2920         HILOG_ERROR("appRunningManager_ is nullptr");
2921         return ERR_INVALID_VALUE;
2922     }
2923 
2924     std::string bundleName = want.GetStringParam("-b");
2925     if (bundleName.empty()) {
2926         HILOG_ERROR("Invalid bundle name");
2927         return ERR_INVALID_VALUE;
2928     }
2929 
2930     if (KillApplicationByUserIdLocked(bundleName, userId)) {
2931         HILOG_ERROR("Failed to kill the application");
2932         return ERR_INVALID_VALUE;
2933     }
2934 
2935     HapModuleInfo hapModuleInfo;
2936     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
2937         HILOG_ERROR("Failed to get HapModuleInfo for TestRunner");
2938         return ERR_INVALID_VALUE;
2939     }
2940 
2941     std::string processName;
2942     MakeProcessName(std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo, processName);
2943     HILOG_INFO("processName = [%{public}s]", processName.c_str());
2944 
2945     // Inspection records
2946     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
2947         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
2948     if (appRecord) {
2949         HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
2950         return ERR_INVALID_VALUE;
2951     }
2952 
2953     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
2954 }
2955 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)2956 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2957     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
2958 {
2959     HILOG_INFO("Enter");
2960     if (!observer) {
2961         HILOG_ERROR("observer nullptr.");
2962         return ERR_INVALID_VALUE;
2963     }
2964 
2965     bool moduleJson = false;
2966     if (!bundleInfo.hapModuleInfos.empty()) {
2967         moduleJson = bundleInfo.hapModuleInfos.back().isModuleJson;
2968     }
2969     if (moduleJson) {
2970         std::string moduleName = want.GetStringParam("-m");
2971         if (moduleName.empty()) {
2972             UserTestAbnormalFinish(observer, "No module name is specified.");
2973             return ERR_INVALID_VALUE;
2974         }
2975 
2976         bool found = false;
2977         for (auto item : bundleInfo.hapModuleInfos) {
2978             if (item.moduleName == moduleName) {
2979                 hapModuleInfo = item;
2980                 found = true;
2981                 break;
2982             }
2983         }
2984         if (!found) {
2985             UserTestAbnormalFinish(observer, "The specified module name is not found.");
2986             return ERR_INVALID_VALUE;
2987         }
2988     }
2989     return ERR_OK;
2990 }
2991 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)2992 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
2993 {
2994     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
2995     if (!observerProxy) {
2996         HILOG_ERROR("Failed to get ITestObserver proxy");
2997         return ERR_INVALID_VALUE;
2998     }
2999     observerProxy->TestFinished(msg, -1);
3000     return ERR_OK;
3001 }
3002 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)3003 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
3004     const BundleInfo &info, const std::string &processName, const int userId)
3005 {
3006     HILOG_INFO("enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
3007     if (!CheckRemoteClient() || !appRunningManager_) {
3008         HILOG_ERROR("Failed to start the process being tested!");
3009         return ERR_INVALID_VALUE;
3010     }
3011 
3012     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name);
3013     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
3014     if (!appExistFlag) {
3015         NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
3016     }
3017     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
3018     if (!appRecord) {
3019         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
3020         return ERR_INVALID_VALUE;
3021     }
3022 
3023     auto isDebug = want.GetBoolParam(DEBUG_APP, false);
3024     HILOG_INFO("Set Debug : %{public}s", (isDebug ? "true" : "false"));
3025     appRecord->SetDebugApp(isDebug);
3026     if (want.GetBoolParam(COLD_START, false)) {
3027         appRecord->SetDebugApp(true);
3028     }
3029 
3030     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
3031     if (!testRecord) {
3032         HILOG_ERROR("Failed to make UserTestRecord!");
3033         return ERR_INVALID_VALUE;
3034     }
3035     testRecord->want = want;
3036     testRecord->observer = observer;
3037     testRecord->isFinished = false;
3038     testRecord->userId = userId;
3039     appRecord->SetUserTestInfo(testRecord);
3040 
3041     int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
3042     uint32_t startFlags = 0x0;
3043     if (info.applicationInfo.debug) {
3044         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
3045     }
3046     StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, info, appInfo->bundleName,
3047         bundleIndex, appExistFlag);
3048 
3049     // If it is empty, the startup failed
3050     if (!appRecord) {
3051         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
3052         return ERR_INVALID_VALUE;
3053     }
3054 
3055     appRecord->SetTaskHandler(taskHandler_);
3056     appRecord->SetEventHandler(eventHandler_);
3057     appRecord->AddModules(appInfo, info.hapModuleInfos);
3058     HILOG_INFO("StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid());
3059 
3060     return ERR_OK;
3061 }
3062 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName,const pid_t & pid)3063 int AppMgrServiceInner::FinishUserTest(
3064     const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid)
3065 {
3066     HILOG_INFO("Enter");
3067     if (bundleName.empty()) {
3068         HILOG_ERROR("Invalid bundle name.");
3069         return ERR_INVALID_VALUE;
3070     }
3071     auto appRecord = GetAppRunningRecordByPid(pid);
3072     if (!appRecord) {
3073         HILOG_ERROR("no such appRecord");
3074         return ERR_INVALID_VALUE;
3075     }
3076 
3077     auto userTestRecord = appRecord->GetUserTestInfo();
3078     if (!userTestRecord) {
3079         HILOG_ERROR("unstart user test");
3080         return ERR_INVALID_VALUE;
3081     }
3082 
3083     FinishUserTestLocked(msg, resultCode, appRecord);
3084 
3085     int ret = KillApplicationByUserIdLocked(bundleName, userTestRecord->userId);
3086     if (ret) {
3087         HILOG_ERROR("Failed to kill process.");
3088         return ret;
3089     }
3090 
3091     return ERR_OK;
3092 }
3093 
FinishUserTestLocked(const std::string & msg,const int64_t & resultCode,const std::shared_ptr<AppRunningRecord> & appRecord)3094 int AppMgrServiceInner::FinishUserTestLocked(
3095     const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord)
3096 {
3097     HILOG_DEBUG("Enter");
3098     if (!appRecord) {
3099         HILOG_ERROR("Invalid appRecord");
3100         return ERR_INVALID_VALUE;
3101     }
3102 
3103     std::lock_guard<ffrt::mutex> lock(userTestLock_);
3104     auto userTestRecord = appRecord->GetUserTestInfo();
3105     if (!userTestRecord) {
3106         HILOG_WARN("not start user test");
3107         return ERR_INVALID_VALUE;
3108     }
3109     if (!userTestRecord->isFinished) {
3110         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
3111         if (!observerProxy) {
3112             HILOG_ERROR("Failed to get ITestObserver proxy");
3113             return ERR_INVALID_VALUE;
3114         }
3115         observerProxy->TestFinished(msg, resultCode);
3116 
3117         userTestRecord->isFinished = true;
3118     }
3119 
3120     return ERR_OK;
3121 }
3122 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo)3123 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)
3124 {
3125     HILOG_DEBUG("Start specified ability.");
3126     if (!CheckRemoteClient()) {
3127         return;
3128     }
3129 
3130     BundleInfo bundleInfo;
3131     HapModuleInfo hapModuleInfo;
3132     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
3133 
3134     int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
3135     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
3136         return;
3137     }
3138 
3139     std::string processName;
3140     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
3141     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, processName);
3142 
3143     std::vector<HapModuleInfo> hapModules;
3144     hapModules.emplace_back(hapModuleInfo);
3145 
3146     std::shared_ptr<AppRunningRecord> appRecord;
3147     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
3148     if (!appRecord) {
3149         bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
3150         if (!appExistFlag) {
3151             NotifyAppRunningStatusEvent(
3152                 bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
3153         }
3154         // new app record
3155         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
3156         if (!appRecord) {
3157             HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
3158             return;
3159         }
3160         if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, hapModuleInfo)) {
3161             appRecord->SetKeepAliveAppState(false, false);
3162             HILOG_DEBUG("The process %{public}s will not keepalive", hapModuleInfo.process.c_str());
3163         }
3164         auto wantPtr = std::make_shared<AAFwk::Want>(want);
3165         if (wantPtr != nullptr) {
3166             appRecord->SetCallerPid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
3167             appRecord->SetCallerUid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
3168             appRecord->SetCallerTokenId(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
3169             appRecord->SetDebugApp(wantPtr->GetBoolParam(DEBUG_APP, false));
3170             if (appRecord->IsDebugApp()) {
3171                 ProcessAppDebug(appRecord, true);
3172             }
3173             appRecord->SetNativeDebug(wantPtr->GetBoolParam("nativeDebug", false));
3174             if (wantPtr->GetBoolParam(COLD_START, false)) {
3175                 appRecord->SetDebugApp(true);
3176             }
3177             appRecord->SetPerfCmd(wantPtr->GetStringParam(PERF_CMD));
3178         }
3179         appRecord->SetProcessAndExtensionType(abilityInfoPtr);
3180         appRecord->SetTaskHandler(taskHandler_);
3181         appRecord->SetEventHandler(eventHandler_);
3182         appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
3183             AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT);
3184         uint32_t startFlags = BuildStartFlags(want, abilityInfo);
3185         int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
3186         StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, bundleInfo, appInfo->bundleName,
3187             bundleIndex, appExistFlag);
3188 
3189         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
3190         appRecord->AddModules(appInfo, hapModules);
3191     } else {
3192         HILOG_DEBUG("process is exist");
3193         auto isDebugApp = want.GetBoolParam(DEBUG_APP, false);
3194         if (isDebugApp && !appRecord->IsDebugApp()) {
3195             ProcessAppDebug(appRecord, isDebugApp);
3196         }
3197 
3198         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
3199         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
3200         if (!moduleRecord) {
3201             HILOG_DEBUG("module record is nullptr, add modules");
3202             appRecord->AddModules(appInfo, hapModules);
3203             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
3204         } else {
3205             HILOG_DEBUG("schedule accept want");
3206             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
3207         }
3208     }
3209 }
3210 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)3211 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
3212 {
3213     if (!response) {
3214         HILOG_ERROR("response is nullptr, register failed.");
3215         return;
3216     }
3217 
3218     pid_t callingPid = IPCSkeleton::GetCallingPid();
3219     pid_t pid = getpid();
3220     if (callingPid != pid) {
3221         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
3222         return;
3223     }
3224 
3225     startSpecifiedAbilityResponse_ = response;
3226 }
3227 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)3228 void AppMgrServiceInner::ScheduleAcceptWantDone(
3229     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
3230 {
3231     HILOG_DEBUG("Schedule accept want done, flag: %{public}s", flag.c_str());
3232 
3233     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
3234     if (!appRecord) {
3235         HILOG_ERROR("Get app record failed.");
3236         return;
3237     }
3238     appRecord->ScheduleAcceptWantDone();
3239 
3240     if (startSpecifiedAbilityResponse_) {
3241         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag);
3242     }
3243 }
3244 
HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)3245 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)
3246 {
3247     HILOG_DEBUG("called start specified ability time out!");
3248     if (!appRunningManager_) {
3249         HILOG_ERROR("appRunningManager_ is nullptr");
3250         return;
3251     }
3252 
3253     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
3254     if (!appRecord) {
3255         HILOG_ERROR("appRecord is nullptr");
3256         return;
3257     }
3258 
3259     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
3260         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
3261     }
3262 
3263     KillApplicationByRecord(appRecord);
3264 }
3265 
ScheduleNewProcessRequestDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)3266 void AppMgrServiceInner::ScheduleNewProcessRequestDone(
3267     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
3268 {
3269     HILOG_DEBUG("ScheduleNewProcessRequestDone, flag: %{public}s", flag.c_str());
3270 
3271     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
3272     if (!appRecord) {
3273         HILOG_ERROR("Get app record failed.");
3274         return;
3275     }
3276     appRecord->ScheduleNewProcessRequestDone();
3277 
3278     if (startSpecifiedAbilityResponse_) {
3279         startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, flag);
3280     }
3281 }
3282 
HandleStartSpecifiedProcessTimeout(const int64_t eventId)3283 void AppMgrServiceInner::HandleStartSpecifiedProcessTimeout(const int64_t eventId)
3284 {
3285     HILOG_DEBUG("called start specified process time out!");
3286     if (!appRunningManager_) {
3287         HILOG_ERROR("appRunningManager_ is nullptr");
3288         return;
3289     }
3290 
3291     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
3292     if (!appRecord) {
3293         HILOG_ERROR("appRecord is nullptr");
3294         return;
3295     }
3296 
3297     if (startSpecifiedAbilityResponse_) {
3298         startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant());
3299     }
3300 }
3301 
UpdateConfiguration(const Configuration & config)3302 int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config)
3303 {
3304     if (!appRunningManager_) {
3305         HILOG_ERROR("appRunningManager_ is null");
3306         return ERR_INVALID_VALUE;
3307     }
3308     CHECK_CALLER_IS_SYSTEM_APP;
3309 
3310     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
3311     if (ret != ERR_OK) {
3312         return ret;
3313     }
3314 
3315     std::vector<std::string> changeKeyV;
3316     configuration_->CompareDifferent(changeKeyV, config);
3317     HILOG_INFO("changeKeyV size :%{public}zu", changeKeyV.size());
3318     if (config.GetItem(AAFwk::GlobalConfigurationKey::THEME).empty() && changeKeyV.empty()) {
3319         HILOG_ERROR("changeKeyV is empty");
3320         return ERR_INVALID_VALUE;
3321     }
3322     configuration_->Merge(changeKeyV, config);
3323     // all app
3324     int32_t result = appRunningManager_->UpdateConfiguration(config);
3325     HandleConfigurationChange(config);
3326     if (result != ERR_OK) {
3327         HILOG_ERROR("update error, not notify");
3328         return result;
3329     }
3330     // notify
3331     std::lock_guard<ffrt::mutex> notifyLock(configurationObserverLock_);
3332     for (auto &observer : configurationObservers_) {
3333         if (observer != nullptr) {
3334             observer->OnConfigurationUpdated(config);
3335         }
3336     }
3337     return result;
3338 }
3339 
HandleConfigurationChange(const Configuration & config)3340 void AppMgrServiceInner::HandleConfigurationChange(const Configuration &config)
3341 {
3342     std::lock_guard lock(appStateCallbacksLock_);
3343     for (const auto &callback : appStateCallbacks_) {
3344         if (callback != nullptr) {
3345             callback->NotifyConfigurationChange(config, currentUserId_);
3346         }
3347     }
3348 }
3349 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)3350 int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
3351 {
3352     HILOG_DEBUG("called");
3353 
3354     if (observer == nullptr) {
3355         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
3356         return ERR_INVALID_VALUE;
3357     }
3358     std::lock_guard<ffrt::mutex> registerLock(configurationObserverLock_);
3359     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
3360         [&observer](const sptr<IConfigurationObserver> &item) {
3361             return (item && item->AsObject() == observer->AsObject());
3362         }
3363     );
3364     if (it != configurationObservers_.end()) {
3365         HILOG_ERROR("AppMgrServiceInner::Register error: observer exist");
3366         return ERR_INVALID_VALUE;
3367     }
3368     configurationObservers_.push_back(observer);
3369     return NO_ERROR;
3370 }
3371 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)3372 int32_t AppMgrServiceInner::UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
3373 {
3374     HILOG_INFO("called");
3375     if (observer == nullptr) {
3376         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
3377         return ERR_INVALID_VALUE;
3378     }
3379     std::lock_guard<ffrt::mutex> unregisterLock(configurationObserverLock_);
3380     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
3381         [&observer](const sptr<IConfigurationObserver> &item) {
3382             return (item && item->AsObject() == observer->AsObject());
3383         }
3384     );
3385     if (it != configurationObservers_.end()) {
3386         configurationObservers_.erase(it);
3387         return NO_ERROR;
3388     }
3389     HILOG_INFO("end");
3390     return ERR_INVALID_VALUE;
3391 }
3392 
InitGlobalConfiguration()3393 void AppMgrServiceInner::InitGlobalConfiguration()
3394 {
3395     if (!configuration_) {
3396         HILOG_ERROR("configuration_ is null");
3397         return;
3398     }
3399 
3400 #ifdef SUPPORT_GRAPHICS
3401     // Currently only this interface is known
3402     auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
3403     HILOG_INFO("current global language is : %{public}s", language.c_str());
3404     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
3405 #endif
3406 
3407     // Assign to default colorMode "light"
3408     HILOG_INFO("current global colorMode is : %{public}s", ConfigurationInner::COLOR_MODE_LIGHT);
3409     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
3410 
3411     // Get input pointer device
3412     std::string hasPointerDevice = system::GetParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "false");
3413     HILOG_INFO("current hasPointerDevice is %{public}s", hasPointerDevice.c_str());
3414     configuration_->AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, hasPointerDevice);
3415 
3416     // Get DeviceType
3417     auto deviceType = GetDeviceType();
3418     HILOG_INFO("current deviceType is %{public}s", deviceType);
3419     configuration_->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType);
3420 }
3421 
GetConfiguration()3422 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
3423 {
3424     return configuration_;
3425 }
3426 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)3427 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
3428 {
3429     HILOG_DEBUG("Kill application by appRecord.");
3430     if (!appRecord || !taskHandler_) {
3431         HILOG_WARN("appRecord or taskHandler_ is nullptr.");
3432         return;
3433     }
3434 
3435     auto pid = appRecord->GetPriorityObject()->GetPid();
3436     appRecord->SetTerminating();
3437     appRecord->ScheduleProcessSecurityExit();
3438 
3439     auto startTime = SystemTimeMillisecond();
3440     std::list<pid_t> pids = {pid};
3441     if (WaitForRemoteProcessExit(pids, startTime)) {
3442         HILOG_INFO("The remote process exited successfully");
3443         return;
3444     }
3445 
3446     auto timeoutTask = [pid, innerService = shared_from_this()]() {
3447         HILOG_INFO("KillProcessByPid %{public}d", pid);
3448         int32_t result = innerService->KillProcessByPid(pid);
3449         if (result < 0) {
3450             HILOG_ERROR("Kill application by app record failed, pid: %{public}d", pid);
3451             return;
3452         }
3453     };
3454     taskHandler_->SubmitTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
3455 }
3456 
SendHiSysEvent(const int32_t innerEventId,const int64_t eventId)3457 void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_t eventId)
3458 {
3459     HILOG_DEBUG("called AppMgrServiceInner SendHiSysEvent!");
3460     if (!appRunningManager_) {
3461         HILOG_ERROR("appRunningManager_ is nullptr");
3462         return;
3463     }
3464 
3465     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
3466     if (!appRecord) {
3467         HILOG_ERROR("appRecord is nullptr");
3468         return;
3469     }
3470     const int bufferLen = 128;
3471     char paramOutBuf[bufferLen] = {0};
3472     const char *hook_mode = "startup:";
3473     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
3474     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
3475         HILOG_DEBUG("SendHiSysEvent, Hook_mode: no handle time out");
3476         return;
3477     }
3478 
3479     std::string eventName = AppExecFwk::AppFreezeType::LIFECYCLE_TIMEOUT;
3480     int32_t pid = appRecord->GetPriorityObject()->GetPid();
3481     int32_t uid = appRecord->GetUid();
3482     std::string packageName = appRecord->GetBundleName();
3483     std::string processName = appRecord->GetProcessName();
3484     std::string msg = AppExecFwk::AppFreezeType::APP_LIFECYCLE_TIMEOUT;
3485     msg += ",";
3486     int typeId = AppExecFwk::AppfreezeManager::TypeAttribute::NORMAL_TIMEOUT;
3487     switch (innerEventId) {
3488         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
3489             msg += EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
3490             break;
3491         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
3492             msg += EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
3493             break;
3494         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
3495             msg += EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
3496             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3497             break;
3498         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
3499             msg += EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
3500             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3501             break;
3502         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
3503             msg += EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
3504             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3505             break;
3506         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
3507             msg += EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT;
3508             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3509             break;
3510         default:
3511             msg += EVENT_MESSAGE_DEFAULT;
3512             break;
3513     }
3514 
3515     HILOG_WARN("LIFECYCLE_TIMEOUT, eventName = %{public}s, uid = %{public}d, pid = %{public}d, \
3516         packageName = %{public}s, processName = %{public}s, msg = %{public}s",
3517         eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
3518     AppfreezeManager::ParamInfo info = {
3519         .typeId = typeId,
3520         .pid = pid,
3521         .eventName = eventName,
3522         .bundleName = packageName,
3523         .msg = msg
3524     };
3525     AppfreezeManager::GetInstance()->LifecycleTimeoutHandle(info);
3526 }
3527 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)3528 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
3529 {
3530     auto appRecord = GetAppRunningRecordByPid(pid);
3531     if (!appRecord) {
3532         HILOG_ERROR("no such appRecord");
3533         return ERR_NAME_NOT_FOUND;
3534     }
3535 
3536     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3537     auto callingPid = IPCSkeleton::GetCallingPid();
3538     if (!isSaCall && callingPid != pid) {
3539         HILOG_ERROR("Permission verify failed.");
3540         return ERR_PERMISSION_DENIED;
3541     }
3542     for (auto &item : appRecord->GetAbilities()) {
3543         tokens.emplace_back(item.first);
3544     }
3545     return ERR_OK;
3546 }
3547 
GetApplicationInfoByProcessID(const int pid,AppExecFwk::ApplicationInfo & application,bool & debug)3548 int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application,
3549     bool &debug)
3550 {
3551     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3552     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
3553     if (!isSaCall && !isShellCall) {
3554         HILOG_ERROR("no permissions.");
3555         return ERR_PERMISSION_DENIED;
3556     }
3557     auto appRecord = GetAppRunningRecordByPid(pid);
3558     if (!appRecord) {
3559         HILOG_ERROR("no such appRecord for PID:%{public}d", pid);
3560         return ERR_NAME_NOT_FOUND;
3561     }
3562 
3563     auto info = appRecord->GetApplicationInfo();
3564     if (info == nullptr) {
3565         HILOG_ERROR("ApplicationInfo is nullptr !");
3566         return ERR_NO_INIT;
3567     }
3568     application = *info;
3569     debug = appRecord->IsDebugApp();
3570     return ERR_OK;
3571 }
3572 
VerifyProcessPermission() const3573 int AppMgrServiceInner::VerifyProcessPermission() const
3574 {
3575     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3576     if (isSaCall) {
3577         return ERR_OK;
3578     }
3579 
3580     if (VerifyAPL()) {
3581         return ERR_OK;
3582     }
3583 
3584     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3585         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
3586     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
3587 }
3588 
VerifyProcessPermission(const std::string & bundleName) const3589 int AppMgrServiceInner::VerifyProcessPermission(const std::string &bundleName) const
3590 {
3591     CHECK_CALLER_IS_SYSTEM_APP;
3592     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3593     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
3594     if (isSaCall || isShellCall) {
3595         return ERR_OK;
3596     }
3597 
3598     if (VerifyAPL()) {
3599         return ERR_OK;
3600     }
3601 
3602     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3603         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
3604     if (isCallingPerm) {
3605         auto callerPid = IPCSkeleton::GetCallingPid();
3606         auto appRecord = GetAppRunningRecordByPid(callerPid);
3607         if (!appRecord || appRecord->GetBundleName() != bundleName) {
3608             HILOG_ERROR("Permission verification failed.");
3609             return ERR_PERMISSION_DENIED;
3610         }
3611     } else {
3612         HILOG_ERROR("Permission verification failed.");
3613         return ERR_PERMISSION_DENIED;
3614     }
3615 
3616     return ERR_OK;
3617 }
3618 
VerifyProcessPermission(const sptr<IRemoteObject> & token) const3619 int AppMgrServiceInner::VerifyProcessPermission(const sptr<IRemoteObject> &token) const
3620 {
3621     CHECK_CALLER_IS_SYSTEM_APP;
3622     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3623     if (isSaCall) {
3624         return ERR_OK;
3625     }
3626 
3627     if (VerifyAPL()) {
3628         return ERR_OK;
3629     }
3630 
3631     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3632         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
3633     if (isCallingPerm) {
3634         auto callerUid = IPCSkeleton::GetCallingUid();
3635         auto appRecord = GetAppRunningRecordByAbilityToken(token);
3636         if (!appRecord || appRecord->GetUid() != callerUid) {
3637             HILOG_ERROR("Permission verification failed.");
3638             return ERR_PERMISSION_DENIED;
3639         }
3640     } else {
3641         HILOG_ERROR("Permission verification failed.");
3642         return ERR_PERMISSION_DENIED;
3643     }
3644 
3645     return ERR_OK;
3646 }
3647 
CheckCallerIsAppGallery()3648 bool AppMgrServiceInner::CheckCallerIsAppGallery()
3649 {
3650     HILOG_DEBUG("called");
3651     if (!appRunningManager_) {
3652         HILOG_ERROR("appRunningManager_ is nullptr");
3653         return false;
3654     }
3655     auto callerPid = IPCSkeleton::GetCallingPid();
3656     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
3657     if (!appRecord) {
3658         HILOG_ERROR("Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
3659         return false;
3660     }
3661     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
3662     if (!bundleMgrHelper) {
3663         HILOG_ERROR("The bundleMgrHelper is nullptr.");
3664         return false;
3665     }
3666     auto callerBundleName = appRecord->GetBundleName();
3667     if (callerBundleName.empty()) {
3668         HILOG_ERROR("callerBundleName is empty.");
3669         return false;
3670     }
3671     std::string appGalleryBundleName;
3672     if (!bundleMgrHelper->QueryAppGalleryBundleName(appGalleryBundleName)) {
3673         HILOG_ERROR("QueryAppGalleryBundleName failed.");
3674         return false;
3675     }
3676     HILOG_DEBUG("callerBundleName:%{public}s, appGalleryBundleName:%{public}s", callerBundleName.c_str(),
3677         appGalleryBundleName.c_str());
3678 
3679     return callerBundleName == appGalleryBundleName;
3680 }
3681 
VerifyAPL() const3682 bool AppMgrServiceInner::VerifyAPL() const
3683 {
3684     if (!appRunningManager_) {
3685         HILOG_ERROR("appRunningManager_ is nullptr");
3686         return false;
3687     }
3688 
3689     auto callerPid = IPCSkeleton::GetCallingPid();
3690     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
3691     if (!appRecord) {
3692         HILOG_ERROR("Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
3693         return false;
3694     }
3695 
3696     auto applicationInfo = appRecord->GetApplicationInfo();
3697     if (!applicationInfo) {
3698         HILOG_ERROR("Get application info failed.");
3699         return false;
3700     }
3701 
3702     auto apl = applicationInfo->appPrivilegeLevel;
3703     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
3704         HILOG_ERROR("caller is not system_basic or system_core.");
3705         return false;
3706     }
3707     return true;
3708 }
3709 
VerifyAccountPermission(const std::string & permissionName,const int userId) const3710 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId) const
3711 {
3712     if (userId != currentUserId_) {
3713         auto isCallingPermAccount = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3714             AAFwk::PermissionConstants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
3715         if (!isCallingPermAccount) {
3716             HILOG_ERROR("%{public}s: Permission accounts verification failed", __func__);
3717             return ERR_PERMISSION_DENIED;
3718         }
3719     }
3720     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(permissionName);
3721     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
3722 }
3723 
VerifyRequestPermission() const3724 int AppMgrServiceInner::VerifyRequestPermission() const
3725 {
3726     auto callerUid = IPCSkeleton::GetCallingUid();
3727 
3728     if (callerUid == ROOT_UID || callerUid == FOUNDATION_UID) {
3729         return ERR_OK;
3730     } else {
3731         HILOG_ERROR("Permission verification failed, callerUid: %{public}d", callerUid);
3732         return ERR_PERMISSION_DENIED;
3733     }
3734 }
3735 
PreStartNWebSpawnProcess(const pid_t hostPid)3736 int AppMgrServiceInner::PreStartNWebSpawnProcess(const pid_t hostPid)
3737 {
3738     HILOG_INFO("called");
3739     if (hostPid <= 0) {
3740         HILOG_ERROR("invalid param, hostPid:%{public}d", hostPid);
3741         return ERR_INVALID_VALUE;
3742     }
3743 
3744     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
3745     if (!nwebSpawnClient) {
3746         HILOG_ERROR("nwebSpawnClient is null");
3747         return ERR_INVALID_VALUE;
3748     }
3749 
3750     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(hostPid);
3751     if (!appRecord) {
3752         HILOG_ERROR("no such app Record, pid:%{public}d", hostPid);
3753         return ERR_INVALID_VALUE;
3754     }
3755 
3756     ErrCode errCode = nwebSpawnClient->PreStartNWebSpawnProcess();
3757     if (FAILED(errCode)) {
3758         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
3759         return ERR_INVALID_VALUE;
3760     }
3761 
3762     return 0;
3763 }
3764 
StartRenderProcess(const pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,int32_t crashFd,pid_t & renderPid)3765 int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam,
3766     int32_t ipcFd, int32_t sharedFd, int32_t crashFd, pid_t &renderPid)
3767 {
3768     HILOG_INFO("start render process, hostPid:%{public}d", hostPid);
3769     if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 ||
3770         crashFd <= 0) {
3771         HILOG_ERROR("invalid param: hostPid:%{public}d renderParam:%{private}s "
3772                     "ipcFd:%{public}d  crashFd:%{public}d sharedFd:%{public}d",
3773                     hostPid, renderParam.c_str(), ipcFd, crashFd, sharedFd);
3774         return ERR_INVALID_VALUE;
3775     }
3776 
3777     if (!appRunningManager_) {
3778         HILOG_ERROR("appRunningManager_ is nullptr, not start render process");
3779         return ERR_INVALID_VALUE;
3780     }
3781 
3782     auto appRecord = GetAppRunningRecordByPid(hostPid);
3783     if (!appRecord) {
3784         HILOG_ERROR("no such appRecord, hostPid:%{public}d", hostPid);
3785         return ERR_INVALID_VALUE;
3786     }
3787 
3788     auto renderRecordMap = appRecord->GetRenderRecordMap();
3789     if (!renderRecordMap.empty() && !ShouldUseMultipleRenderProcess(deviceType_)) {
3790         for (auto iter : renderRecordMap) {
3791             if (iter.second != nullptr) {
3792                 renderPid = iter.second->GetPid();
3793                 if (ProcessExist(renderPid)) {
3794                     HILOG_WARN("already exist render process,do not request again, renderPid:%{public}d", renderPid);
3795                     return ERR_ALREADY_EXIST_RENDER;
3796                 }
3797                 auto scheduler = iter.second->GetScheduler();
3798                 if (scheduler) {
3799                     HILOG_WARN("render process not realy exist, renderPid:%{public}d", renderPid);
3800                     OnRenderRemoteDied(scheduler->AsObject());
3801                 }
3802             }
3803         }
3804     }
3805 
3806     // The phone device allows a maximum of 40 render processes to be created.
3807     if (deviceType_ == "default" &&
3808         renderRecordMap.size() >= PHONE_MAX_RENDER_PROCESS_NUM) {
3809         HILOG_ERROR(
3810             "Reaching the maximum render process limitation, hostPid:%{public}d",
3811             hostPid);
3812         return ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION;
3813     }
3814 
3815     auto renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam, ipcFd, sharedFd, crashFd, appRecord);
3816     if (!renderRecord) {
3817         HILOG_ERROR("create render record failed, hostPid:%{public}d", hostPid);
3818         return ERR_INVALID_VALUE;
3819     }
3820 
3821     return StartRenderProcessImpl(renderRecord, appRecord, renderPid);
3822 }
3823 
AttachRenderProcess(const pid_t pid,const sptr<IRenderScheduler> & scheduler)3824 void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler)
3825 {
3826     HILOG_DEBUG("attach render process start");
3827     if (pid <= 0) {
3828         HILOG_ERROR("invalid render process pid:%{public}d", pid);
3829         return;
3830     }
3831     if (!scheduler) {
3832         HILOG_ERROR("render scheduler is null");
3833         return;
3834     }
3835 
3836     if (!appRunningManager_) {
3837         HILOG_ERROR("appRunningManager_ is null");
3838         return;
3839     }
3840 
3841     HILOG_INFO("attach render process pid:%{public}d", pid);
3842     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
3843     if (!appRecord) {
3844         HILOG_ERROR("no such app Record, pid:%{public}d", pid);
3845         return;
3846     }
3847 
3848     auto renderRecord = appRecord->GetRenderRecordByPid(pid);
3849     if (!renderRecord) {
3850         HILOG_ERROR("no such render Record, pid:%{public}d", pid);
3851         return;
3852     }
3853 
3854     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
3855     appDeathRecipient->SetTaskHandler(taskHandler_);
3856     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
3857     appDeathRecipient->SetIsRenderProcess(true);
3858     renderRecord->SetScheduler(scheduler);
3859     renderRecord->SetDeathRecipient(appDeathRecipient);
3860     renderRecord->RegisterDeathRecipient();
3861 
3862     // notify fd to render process
3863     scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(),
3864                                renderRecord->GetSharedFd(),
3865                                renderRecord->GetCrashFd());
3866 }
3867 
GenerateRenderUid(int32_t & renderUid)3868 bool AppMgrServiceInner::GenerateRenderUid(int32_t &renderUid)
3869 {
3870     std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
3871     int32_t uid = lastRenderUid_ + 1;
3872     bool needSecondScan = true;
3873     if (uid > Constants::END_UID_FOR_RENDER_PROCESS) {
3874         uid = Constants::START_UID_FOR_RENDER_PROCESS;
3875         needSecondScan = false;
3876     }
3877 
3878     if (renderUidSet_.empty()) {
3879         renderUid = uid;
3880         renderUidSet_.insert(renderUid);
3881         lastRenderUid_ = renderUid;
3882         return true;
3883     }
3884 
3885     for (int32_t i = uid; i <= Constants::END_UID_FOR_RENDER_PROCESS; i++) {
3886         if (renderUidSet_.find(i) == renderUidSet_.end()) {
3887             renderUid = i;
3888             renderUidSet_.insert(renderUid);
3889             lastRenderUid_ = renderUid;
3890             return true;
3891         }
3892     }
3893 
3894     if (needSecondScan) {
3895         for (int32_t i = Constants::START_UID_FOR_RENDER_PROCESS; i <= lastRenderUid_; i++) {
3896             if (renderUidSet_.find(i) == renderUidSet_.end()) {
3897                 renderUid = i;
3898                 renderUidSet_.insert(renderUid);
3899                 lastRenderUid_ = renderUid;
3900                 return true;
3901             }
3902         }
3903     }
3904 
3905     return false;
3906 }
3907 
StartRenderProcessImpl(const std::shared_ptr<RenderRecord> & renderRecord,const std::shared_ptr<AppRunningRecord> appRecord,pid_t & renderPid)3908 int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
3909     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid)
3910 {
3911     if (!renderRecord || !appRecord) {
3912         HILOG_ERROR("renderRecord or appRecord is nullptr.");
3913         return ERR_INVALID_VALUE;
3914     }
3915 
3916     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
3917     if (!nwebSpawnClient) {
3918         HILOG_ERROR("nwebSpawnClient is null");
3919         return ERR_INVALID_VALUE;
3920     }
3921 
3922     int32_t renderUid = Constants::INVALID_UID;
3923     if (!GenerateRenderUid(renderUid)) {
3924         HILOG_ERROR("Generate renderUid failed");
3925         return ERR_INVALID_OPERATION;
3926     }
3927 
3928     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
3929     startMsg.renderParam = renderRecord->GetRenderParam();
3930     startMsg.uid = renderUid;
3931     startMsg.gid = renderUid;
3932     startMsg.code = 0; // 0: DEFAULT
3933     pid_t pid = 0;
3934     ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid);
3935     if (FAILED(errCode)) {
3936         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
3937         std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
3938         renderUidSet_.erase(renderUid);
3939         return ERR_INVALID_VALUE;
3940     }
3941     renderPid = pid;
3942     renderRecord->SetPid(pid);
3943     renderRecord->SetUid(renderUid);
3944     appRecord->AddRenderRecord(renderRecord);
3945     HILOG_INFO("start render process success, hostPid:%{public}d, hostUid:%{public}d, pid:%{public}d, uid:%{public}d",
3946         renderRecord->GetHostPid(), renderRecord->GetHostUid(), pid, renderUid);
3947     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessCreated(renderRecord);
3948     return 0;
3949 }
3950 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)3951 int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
3952 {
3953     if (remoteClientManager_ == nullptr) {
3954         HILOG_ERROR("remoteClientManager_ is null");
3955         return ERR_INVALID_VALUE;
3956     }
3957     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
3958     if (!nwebSpawnClient) {
3959         HILOG_ERROR("nwebSpawnClient is null");
3960         return ERR_INVALID_VALUE;
3961     }
3962 
3963     AppSpawnStartMsg startMsg;
3964     startMsg.pid = renderPid;
3965     startMsg.code = 1; // 1: GET_RENDER_TERMINATION_STATUS
3966     ErrCode errCode = nwebSpawnClient->GetRenderProcessTerminationStatus(startMsg, status);
3967     if (FAILED(errCode)) {
3968         HILOG_ERROR("failed to get render process termination status, errCode %{public}08x", errCode);
3969         return ERR_INVALID_VALUE;
3970     }
3971     HILOG_DEBUG("Get render process termination status success, renderPid:%{public}d, status:%{public}d",
3972         renderPid, status);
3973     return 0;
3974 }
3975 
OnRenderRemoteDied(const wptr<IRemoteObject> & remote)3976 void AppMgrServiceInner::OnRenderRemoteDied(const wptr<IRemoteObject> &remote)
3977 {
3978     HILOG_ERROR("On render remote died.");
3979     if (appRunningManager_) {
3980         auto renderRecord = appRunningManager_->OnRemoteRenderDied(remote);
3981         if (renderRecord) {
3982             {
3983                 std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
3984                 renderUidSet_.erase(renderRecord->GetUid());
3985             }
3986             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
3987         }
3988     }
3989 }
3990 
BuildStartFlags(const AAFwk::Want & want,const AbilityInfo & abilityInfo)3991 uint32_t AppMgrServiceInner::BuildStartFlags(const AAFwk::Want &want, const AbilityInfo &abilityInfo)
3992 {
3993     uint32_t startFlags = 0x0;
3994     if (want.GetBoolParam("coldStart", false)) {
3995         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::COLD_START);
3996     }
3997 
3998     if (want.GetIntParam(DLP_PARAMS_INDEX, 0) != 0) {
3999         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DLP_MANAGER);
4000     }
4001 
4002     if (abilityInfo.extensionAbilityType == ExtensionAbilityType::BACKUP) {
4003         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::BACKUP_EXTENSION);
4004     }
4005 
4006     if (abilityInfo.applicationInfo.debug) {
4007         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
4008     }
4009     if (abilityInfo.applicationInfo.asanEnabled) {
4010 	    startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::ASANENABLED);
4011     }
4012     if (want.GetBoolParam("nativeDebug", false)) {
4013         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::NATIVEDEBUG);
4014     }
4015     if (abilityInfo.applicationInfo.gwpAsanEnabled) {
4016         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::GWP_ENABLED_FORCE);
4017     }
4018     if (abilityInfo.applicationInfo.isSystemApp) {
4019         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::GWP_ENABLED_NORMAL);
4020     }
4021 
4022     return startFlags;
4023 }
4024 
AddWatchParameter()4025 void AppMgrServiceInner::AddWatchParameter()
4026 {
4027     HILOG_INFO("%{public}s called.", __func__);
4028     auto context = new (std::nothrow) std::weak_ptr<AppMgrServiceInner>(shared_from_this());
4029     int ret = WatchParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, PointerDeviceEventCallback,
4030         context);
4031     if (ret != 0) {
4032         HILOG_ERROR("watch parameter %{public}s failed with %{public}d.",
4033             AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, ret);
4034     }
4035 }
4036 
InitFocusListener()4037 void AppMgrServiceInner::InitFocusListener()
4038 {
4039     HILOG_INFO("begin initFocus listener.");
4040     if (focusListener_) {
4041         return;
4042     }
4043 
4044     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
4045     auto registerTask = [innerService = shared_from_this()]() {
4046         if (innerService) {
4047             HILOG_INFO("RegisterFocusListener task");
4048             innerService->RegisterFocusListener();
4049         }
4050     };
4051     if (taskHandler_) {
4052         taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
4053         HILOG_INFO("Submit RegisterFocusListenerTask");
4054     }
4055 }
4056 
RegisterFocusListener()4057 void AppMgrServiceInner::RegisterFocusListener()
4058 {
4059     HILOG_INFO("RegisterFocusListener begin");
4060     if (!focusListener_) {
4061         HILOG_ERROR("no focusListener_");
4062         return;
4063     }
4064     WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
4065     HILOG_INFO("RegisterFocusListener end");
4066 }
4067 
FreeFocusListener()4068 void AppMgrServiceInner::FreeFocusListener()
4069 {
4070     HILOG_INFO("FreeFocusListener begin");
4071     if (!focusListener_) {
4072         HILOG_ERROR("no focusListener_");
4073         return;
4074     }
4075     WindowManager::GetInstance().UnregisterFocusChangedListener(focusListener_);
4076     focusListener_ = nullptr;
4077     HILOG_INFO("FreeFocusListener end");
4078 }
4079 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)4080 void AppMgrServiceInner::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
4081 {
4082     if (!focusChangeInfo) {
4083         HILOG_WARN("focused, invalid focusChangeInfo");
4084         return;
4085     }
4086     HILOG_INFO("focused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
4087 
4088     if (focusChangeInfo->pid_ <= 0) {
4089         HILOG_ERROR("invalid pid:%{public}d", focusChangeInfo->pid_);
4090         return;
4091     }
4092 
4093     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
4094     if (!appRecord) {
4095         HILOG_ERROR("focused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
4096         return;
4097     }
4098 
4099     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, true)) {
4100         HILOG_DEBUG("only change ability focus state, do not change process or application focus state.");
4101         return;
4102     }
4103 
4104     bool needNotifyApp = appRunningManager_->IsApplicationFirstFocused(*appRecord);
4105     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
4106         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, true);
4107     }
4108     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
4109 }
4110 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)4111 void AppMgrServiceInner::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
4112 {
4113     if (!focusChangeInfo) {
4114         HILOG_WARN("unfocused, invalid focusChangeInfo");
4115         return;
4116     }
4117     HILOG_DEBUG("unfocused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
4118 
4119     if (focusChangeInfo->pid_ <= 0) {
4120         HILOG_ERROR("invalid pid:%{public}d", focusChangeInfo->pid_);
4121         return;
4122     }
4123 
4124     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
4125     if (!appRecord) {
4126         HILOG_ERROR("unfocused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
4127         return;
4128     }
4129 
4130     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, false)) {
4131         HILOG_DEBUG("only change ability from focus to unfocus, do not change process or application focus state.");
4132         return;
4133     }
4134 
4135     bool needNotifyApp = appRunningManager_->IsApplicationUnfocused(appRecord->GetBundleName());
4136     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp, true);
4137     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
4138 }
4139 
InitWindowVisibilityChangedListener()4140 void AppMgrServiceInner::InitWindowVisibilityChangedListener()
4141 {
4142     HILOG_DEBUG("Begin.");
4143     if (windowVisibilityChangedListener_ != nullptr) {
4144         HILOG_WARN("Visibility listener has been initiated.");
4145         return;
4146     }
4147     windowVisibilityChangedListener_ =
4148         new (std::nothrow) WindowVisibilityChangedListener(weak_from_this(), taskHandler_);
4149     auto registerTask = [innerService = weak_from_this()] () {
4150         auto inner = innerService.lock();
4151         if (inner == nullptr) {
4152             HILOG_ERROR("Service inner is nullptr.");
4153             return;
4154         }
4155         if (inner->windowVisibilityChangedListener_ == nullptr) {
4156             HILOG_ERROR("Window visibility changed listener is nullptr.");
4157             return;
4158         }
4159         WindowManager::GetInstance().RegisterVisibilityChangedListener(inner->windowVisibilityChangedListener_);
4160     };
4161 
4162     if (taskHandler_ == nullptr) {
4163         HILOG_ERROR("Task handler is nullptr.");
4164         return;
4165     }
4166     taskHandler_->SubmitTask(registerTask, "RegisterVisibilityListener.", REGISTER_VISIBILITY_DELAY);
4167     HILOG_DEBUG("End.");
4168 }
4169 
FreeWindowVisibilityChangedListener()4170 void AppMgrServiceInner::FreeWindowVisibilityChangedListener()
4171 {
4172     HILOG_DEBUG("Called.");
4173     if (windowVisibilityChangedListener_ == nullptr) {
4174         HILOG_WARN("Visibility listener has been freed.");
4175         return;
4176     }
4177     WindowManager::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_);
4178 }
4179 
HandleWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)4180 void AppMgrServiceInner::HandleWindowVisibilityChanged(
4181     const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
4182 {
4183     HILOG_DEBUG("Called.");
4184     if (windowVisibilityInfos.empty()) {
4185         HILOG_WARN("Window visibility info is empty.");
4186         return;
4187     }
4188     if (appRunningManager_ == nullptr) {
4189         HILOG_ERROR("App running manager is nullptr.");
4190         return;
4191     }
4192     appRunningManager_->OnWindowVisibilityChanged(windowVisibilityInfos);
4193 }
4194 
PointerDeviceEventCallback(const char * key,const char * value,void * context)4195 void AppMgrServiceInner::PointerDeviceEventCallback(const char *key, const char *value, void *context)
4196 {
4197     HILOG_INFO("%{public}s called.", __func__);
4198     auto weak = static_cast<std::weak_ptr<AppMgrServiceInner>*>(context);
4199     if (weak == nullptr) {
4200         HILOG_ERROR("context is nullptr.");
4201         return;
4202     }
4203 
4204     auto appMgrServiceInner = weak->lock();
4205     if (appMgrServiceInner == nullptr) {
4206         HILOG_ERROR("app manager service inner is nullptr.");
4207         return;
4208     }
4209 
4210     if ((strcmp(key, AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE) != 0) ||
4211         ((strcmp(value, "true") != 0) && (strcmp(value, "false") != 0))) {
4212         HILOG_ERROR("key %{public}s or value %{public}s mismatch.", key, value);
4213         return;
4214     }
4215 
4216     Configuration changeConfig;
4217     if (!changeConfig.AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, value)) {
4218         HILOG_ERROR("add %{public}s item to configuration failed.", key);
4219         return;
4220     }
4221 
4222     HILOG_DEBUG("update config %{public}s to %{public}s", key, value);
4223     auto result = IN_PROCESS_CALL(appMgrServiceInner->UpdateConfiguration(changeConfig));
4224     if (result != 0) {
4225         HILOG_ERROR("update config failed with %{public}d, key: %{public}s, value: %{public}s.", result, key, value);
4226         return;
4227     }
4228 }
4229 
GetAppRunningStateByBundleName(const std::string & bundleName)4230 bool AppMgrServiceInner::GetAppRunningStateByBundleName(const std::string &bundleName)
4231 {
4232     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4233     HILOG_DEBUG("function called.");
4234     if (!appRunningManager_) {
4235         HILOG_ERROR("app running manager is nullptr.");
4236         return false;
4237     }
4238 
4239     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4240         HILOG_ERROR("Permission deny, not SA.");
4241         return false;
4242     }
4243 
4244     return appRunningManager_->GetAppRunningStateByBundleName(bundleName);
4245 }
4246 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)4247 int32_t AppMgrServiceInner::NotifyLoadRepairPatch(const std::string &bundleName,
4248     const sptr<IQuickFixCallback> &callback)
4249 {
4250     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4251     HILOG_DEBUG("function called.");
4252     if (!appRunningManager_) {
4253         HILOG_ERROR("app running manager is nullptr.");
4254         return ERR_INVALID_OPERATION;
4255     }
4256 
4257     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
4258         HILOG_ERROR("Permission deny, not quick_fix.");
4259         return ERR_PERMISSION_DENIED;
4260     }
4261 
4262     return appRunningManager_->NotifyLoadRepairPatch(bundleName, callback);
4263 }
4264 
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)4265 int32_t AppMgrServiceInner::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
4266 {
4267     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4268     HILOG_DEBUG("function called.");
4269     if (!appRunningManager_) {
4270         HILOG_ERROR("app running manager is nullptr.");
4271         return ERR_INVALID_OPERATION;
4272     }
4273 
4274     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
4275         HILOG_ERROR("Permission deny, not quick_fix.");
4276         return ERR_PERMISSION_DENIED;
4277     }
4278 
4279     return appRunningManager_->NotifyHotReloadPage(bundleName, callback);
4280 }
4281 
4282 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
SetContinuousTaskProcess(int32_t pid,bool isContinuousTask)4283 int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask)
4284 {
4285     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
4286     if (!isSaCall) {
4287         HILOG_ERROR("callerToken not SA %{public}s", __func__);
4288         return ERR_INVALID_VALUE;
4289     }
4290 
4291     if (!appRunningManager_) {
4292         HILOG_ERROR("app running manager is nullptr.");
4293         return ERR_INVALID_OPERATION;
4294     }
4295 
4296     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(pid);
4297     if (!appRecord) {
4298         HILOG_ERROR("Get app running record by pid failed. pid: %{public}d", pid);
4299         return false;
4300     }
4301     appRecord->SetContinuousTaskAppState(isContinuousTask);
4302     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
4303 
4304     return ERR_OK;
4305 }
4306 #endif
4307 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)4308 int32_t AppMgrServiceInner::NotifyUnLoadRepairPatch(const std::string &bundleName,
4309     const sptr<IQuickFixCallback> &callback)
4310 {
4311     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4312     HILOG_DEBUG("function called.");
4313     if (!appRunningManager_) {
4314         HILOG_ERROR("app running manager is nullptr.");
4315         return ERR_INVALID_OPERATION;
4316     }
4317 
4318     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
4319         HILOG_ERROR("Permission deny, not quick_fix.");
4320         return ERR_PERMISSION_DENIED;
4321     }
4322 
4323     return appRunningManager_->NotifyUnLoadRepairPatch(bundleName, callback);
4324 }
4325 
AppRecoveryNotifyApp(int32_t pid,const std::string & bundleName,FaultDataType faultType,const std::string & markers)4326 void AppMgrServiceInner::AppRecoveryNotifyApp(int32_t pid, const std::string& bundleName,
4327     FaultDataType faultType, const std::string& markers)
4328 {
4329     HILOG_INFO("AppRecovery NotifyApp to kill is: bundleName: %{public}s, faultType: %{public}d, pid: %{public}d",
4330         bundleName.c_str(), faultType, pid);
4331     if (faultType != FaultDataType::APP_FREEZE) {
4332         KillProcessByPid(pid);
4333         return;
4334     }
4335 
4336     std::string timeOutName = "waitSaveTask" + std::to_string(pid) + bundleName;
4337     if (markers == "appRecovery") {
4338         if (taskHandler_->CancelTask(timeOutName)) {
4339             KillProcessByPid(pid);
4340         }
4341         return;
4342     }
4343 
4344     if (markers != "recoveryTimeout") {
4345         return;
4346     }
4347     auto waitSaveTask = [pid, bundleName, innerService = shared_from_this()]() {
4348         auto appRecord = innerService->GetAppRunningRecordByPid(pid);
4349         if (appRecord == nullptr) {
4350             HILOG_ERROR("no such appRecord");
4351             return;
4352         }
4353         std::string name = appRecord->GetBundleName();
4354         if (bundleName == name) {
4355             HILOG_INFO("waitSaveTask timeout %{public}s,pid == %{public}d is going to exit due to AppRecovery.",
4356                 bundleName.c_str(), pid);
4357             innerService->KillProcessByPid(pid);
4358         }
4359     };
4360     constexpr int32_t timeOut = 2000;
4361     taskHandler_->SubmitTask(waitSaveTask, timeOutName, timeOut);
4362 }
4363 
NotifyAppFault(const FaultData & faultData)4364 int32_t AppMgrServiceInner::NotifyAppFault(const FaultData &faultData)
4365 {
4366     HILOG_DEBUG("called.");
4367     int32_t callerUid = IPCSkeleton::GetCallingUid();
4368     int32_t pid = IPCSkeleton::GetCallingPid();
4369     auto appRecord = GetAppRunningRecordByPid(pid);
4370     if (appRecord == nullptr) {
4371         HILOG_ERROR("no such appRecord");
4372         return ERR_INVALID_VALUE;
4373     }
4374     std::string bundleName = appRecord->GetBundleName();
4375 
4376     if (faultData.faultType == FaultDataType::APP_FREEZE) {
4377         if (faultData.timeoutMarkers != "" &&
4378             !taskHandler_->CancelTask(faultData.timeoutMarkers)) {
4379             return ERR_OK;
4380         }
4381 
4382         if (appRecord->IsDebugApp()) {
4383             return ERR_OK;
4384         }
4385 
4386         if (faultData.waitSaveState) {
4387             AppRecoveryNotifyApp(pid, bundleName, FaultDataType::APP_FREEZE, "recoveryTimeout");
4388         }
4389     }
4390 
4391     auto notifyAppTask = [appRecord, pid, callerUid, bundleName, faultData, innerService = shared_from_this()]() {
4392         if (faultData.faultType == FaultDataType::APP_FREEZE) {
4393             AppfreezeManager::AppInfo info = {
4394                 .pid = pid,
4395                 .uid = callerUid,
4396                 .bundleName = bundleName,
4397                 .processName = bundleName,
4398             };
4399             AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
4400         }
4401 
4402         HILOG_WARN("FaultData is: name: %{public}s, faultType: %{public}d, uid: %{public}d, pid: %{public}d,"
4403             "bundleName: %{public}s, faultData.forceExit==%{public}d, faultData.waitSaveState==%{public}d",
4404             faultData.errorObject.name.c_str(), faultData.faultType,
4405             callerUid, pid, bundleName.c_str(), faultData.forceExit, faultData.waitSaveState);
4406 
4407         if (faultData.forceExit && !faultData.waitSaveState) {
4408             HILOG_INFO("FaultData %{public}s,pid == %{public}d is going to exit due to %{public}s.",
4409                 bundleName.c_str(), pid, innerService->FaultTypeToString(faultData.faultType).c_str());
4410             innerService->KillProcessByPid(pid);
4411             return;
4412         }
4413     };
4414 
4415     if (AppExecFwk::AppfreezeManager::GetInstance()->IsProcessDebug(pid, bundleName)) {
4416         HILOG_WARN("heap dump, don't reportEvent and kill:%{public}s, pid:%{public}d, bundleName:%{public}s.",
4417             faultData.errorObject.name.c_str(), pid, bundleName.c_str());
4418     } else {
4419         taskHandler_->SubmitTask(notifyAppTask, "notifyAppFaultTask");
4420     }
4421     return ERR_OK;
4422 }
4423 
TimeoutNotifyApp(int32_t pid,int32_t uid,const std::string & bundleName,const FaultData & faultData)4424 void AppMgrServiceInner::TimeoutNotifyApp(int32_t pid, int32_t uid,
4425     const std::string& bundleName, const FaultData &faultData)
4426 {
4427     if (faultData.faultType == FaultDataType::APP_FREEZE) {
4428         AppfreezeManager::AppInfo info = {
4429             .pid = pid,
4430             .uid = uid,
4431             .bundleName = bundleName,
4432             .processName = bundleName,
4433         };
4434         AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
4435     }
4436 }
4437 
NotifyAppFaultBySA(const AppFaultDataBySA & faultData)4438 int32_t AppMgrServiceInner::NotifyAppFaultBySA(const AppFaultDataBySA &faultData)
4439 {
4440     if (remoteClientManager_ == nullptr) {
4441         HILOG_ERROR("The remoteClientManager_ is nullptr.");
4442         return ERR_NO_INIT;
4443     }
4444     std::string callerBundleName;
4445     if (auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); bundleMgrHelper != nullptr) {
4446         int32_t callingUid = IPCSkeleton::GetCallingUid();
4447         IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
4448     }
4449 #ifdef ABILITY_FAULT_AND_EXIT_TEST
4450     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) ||
4451         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
4452 #else
4453     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) || callerBundleName == SCENE_BOARD_BUNDLE_NAME) {
4454 #endif
4455         int32_t pid = faultData.pid;
4456         auto record = GetAppRunningRecordByPid(pid);
4457         if (record == nullptr) {
4458             HILOG_ERROR("no such AppRunningRecord");
4459             return ERR_INVALID_VALUE;
4460         }
4461 
4462         FaultData transformedFaultData = ConvertDataTypes(faultData);
4463         int32_t uid = record->GetUid();
4464         std::string bundleName = record->GetBundleName();
4465 
4466         if (faultData.errorObject.name == "appRecovery") {
4467             AppRecoveryNotifyApp(pid, bundleName, faultData.faultType, "appRecovery");
4468             return ERR_OK;
4469         }
4470 
4471         if (transformedFaultData.timeoutMarkers.empty()) {
4472             transformedFaultData.timeoutMarkers = "notifyFault:" + transformedFaultData.errorObject.name +
4473                 std::to_string(pid) + "-" + std::to_string(SystemTimeMillisecond());
4474         }
4475         const int64_t timeout = 11000;
4476         if (faultData.faultType == FaultDataType::APP_FREEZE) {
4477             if (!AppExecFwk::AppfreezeManager::GetInstance()->IsHandleAppfreeze(bundleName) || record->IsDebugApp()) {
4478                 return ERR_OK;
4479             }
4480             auto timeoutNotifyApp = std::bind(&AppMgrServiceInner::TimeoutNotifyApp, this,
4481                 pid, uid, bundleName, transformedFaultData);
4482             taskHandler_->SubmitTask(timeoutNotifyApp, transformedFaultData.timeoutMarkers, timeout);
4483         }
4484         record->NotifyAppFault(transformedFaultData);
4485         HILOG_WARN("FaultDataBySA is: name: %{public}s, faultType: %{public}s, uid: %{public}d,"
4486             "pid: %{public}d, bundleName: %{public}s", faultData.errorObject.name.c_str(),
4487             FaultTypeToString(faultData.faultType).c_str(), uid, pid, bundleName.c_str());
4488     } else {
4489         HILOG_DEBUG("this is not called by SA.");
4490         return AAFwk::CHECK_PERMISSION_FAILED;
4491     }
4492     return ERR_OK;
4493 }
4494 
4495 FaultData AppMgrServiceInner::ConvertDataTypes(const AppFaultDataBySA &faultData)
4496 {
4497     FaultData newfaultData;
4498     newfaultData.faultType = faultData.faultType;
4499     newfaultData.errorObject.message =
4500         "\nFault time:" + AbilityRuntime::TimeUtil::FormatTime("%Y/%m/%d-%H:%M:%S") + "\n";
4501     newfaultData.errorObject.message += faultData.errorObject.message;
4502     newfaultData.errorObject.name = faultData.errorObject.name;
4503     newfaultData.errorObject.stack = faultData.errorObject.stack;
4504     newfaultData.timeoutMarkers = faultData.timeoutMarkers;
4505     newfaultData.waitSaveState = faultData.waitSaveState;
4506     newfaultData.notifyApp = faultData.notifyApp;
4507     newfaultData.forceExit = faultData.forceExit;
4508     newfaultData.token = faultData.token;
4509     newfaultData.state = faultData.state;
4510     return newfaultData;
4511 }
4512 
4513 std::string AppMgrServiceInner::FaultTypeToString(AppExecFwk::FaultDataType type)
4514 {
4515     std::string typeStr = "UNKNOWN";
4516     switch (type) {
4517         case AppExecFwk::FaultDataType::CPP_CRASH:
4518             typeStr = "CPP_CRASH";
4519             break;
4520         case AppExecFwk::FaultDataType::JS_ERROR:
4521             typeStr = "JS_ERROR";
4522             break;
4523         case AppExecFwk::FaultDataType::APP_FREEZE:
4524             typeStr = "APP_FREEZE";
4525             break;
4526         case AppExecFwk::FaultDataType::PERFORMANCE_CONTROL:
4527             typeStr = "PERFORMANCE_CONTROL";
4528             break;
4529         case AppExecFwk::FaultDataType::RESOURCE_CONTROL:
4530             typeStr = "RESOURCE_CONTROL";
4531             break;
4532         default:
4533             break;
4534     }
4535     return typeStr;
4536 }
4537 
4538 bool AppMgrServiceInner::IsSharedBundleRunning(const std::string &bundleName, uint32_t versionCode)
4539 {
4540     if (!CheckGetRunningInfoPermission()) {
4541         return false;
4542     }
4543     for (const auto &it : runningSharedBundleList_) {
4544         for (const auto &item : it.second) {
4545             if (item.bundleName == bundleName && item.versionCode == versionCode) {
4546                 return true;
4547             }
4548         }
4549     }
4550     return false;
4551 }
4552 
4553 int32_t AppMgrServiceInner::IsApplicationRunning(const std::string &bundleName, bool &isRunning)
4554 {
4555     HILOG_DEBUG("Called, bundleName: %{public}s", bundleName.c_str());
4556     CHECK_CALLER_IS_SYSTEM_APP;
4557     if (!CheckGetRunningInfoPermission()) {
4558         HILOG_ERROR("Permission verification failed.");
4559         return ERR_PERMISSION_DENIED;
4560     }
4561 
4562     isRunning = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleName);
4563     return ERR_OK;
4564 }
4565 
4566 int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &want) const
4567 {
4568     auto&& bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
4569     if (bundleMgrHelper == nullptr) {
4570         HILOG_ERROR("Get bundle manager helper error.");
4571         return ERR_INVALID_OPERATION;
4572     }
4573 
4574     if (appRunningManager_ == nullptr) {
4575         HILOG_ERROR("appRunningManager_ is nullptr.");
4576         return ERR_INVALID_OPERATION;
4577     }
4578     HILOG_INFO("debuggablePipe bundleName:%{public}s", want.GetElement().GetBundleName().c_str());
4579     HILOG_INFO("debuggablePipe moduleName:%{public}s", want.GetElement().GetModuleName().c_str());
4580     HILOG_INFO("debuggablePipe abilityName:%{public}s", want.GetElement().GetAbilityName().c_str());
4581 
4582     AbilityInfo abilityInfo;
4583     auto userId = GetCurrentAccountId();
4584     IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->QueryAbilityInfo(want, GetFlag(), userId, abilityInfo));
4585     BundleInfo bundleInfo;
4586     HapModuleInfo hapModuleInfo;
4587     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
4588     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, 0)) {
4589         HILOG_ERROR("GetBundleAndHapInfo failed");
4590         return ERR_INVALID_OPERATION;
4591     }
4592 
4593     std::string processName;
4594     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
4595     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, 0, processName);
4596 
4597     auto&& appRecord =
4598         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
4599     if (appRecord == nullptr) {
4600         HILOG_ERROR("The appRecord not found.");
4601         return ERR_INVALID_OPERATION;
4602     }
4603 
4604     bool isSandboxApp = want.GetBoolParam(ENTER_SANDBOX, false);
4605     if (isSandboxApp) {
4606         HILOG_INFO("debuggablePipe sandbox: true");
4607     }
4608     auto&& cmd = want.GetStringParam(PERF_CMD);
4609     if (cmd.size() == 0) {
4610         cmd = want.GetStringParam(DEBUG_CMD);
4611         HILOG_INFO("debuggablePipe debugCmd:%{public}s", cmd.c_str());
4612         if (!appInfo->debug) {
4613             HILOG_ERROR("The app is not debug mode.");
4614             return ERR_INVALID_OPERATION;
4615         }
4616         return StartPerfProcess(appRecord, "", cmd, isSandboxApp);
4617     } else {
4618         return StartPerfProcess(appRecord, cmd, "", isSandboxApp);
4619     }
4620 }
4621 
4622 int32_t AppMgrServiceInner::GetFlag() const
4623 {
4624     return AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION |
4625         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION |
4626         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA;
4627 }
4628 
4629 int32_t AppMgrServiceInner::GetCurrentAccountId() const
4630 {
4631     std::vector<int32_t> osActiveAccountIds;
4632     ErrCode ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4633         QueryActiveOsAccountIds(osActiveAccountIds);
4634     if (ret != ERR_OK) {
4635         HILOG_ERROR("QueryActiveOsAccountIds failed.");
4636         return DEFAULT_USER_ID;
4637     }
4638     if (osActiveAccountIds.empty()) {
4639         HILOG_ERROR("%{public}s, QueryActiveOsAccountIds is empty, no accounts.", __func__);
4640         return DEFAULT_USER_ID;
4641     }
4642 
4643     return osActiveAccountIds.front();
4644 }
4645 
4646 void AppMgrServiceInner::SetRunningSharedBundleList(const std::string &bundleName,
4647     const std::vector<BaseSharedBundleInfo> baseSharedBundleInfoList)
4648 {
4649     runningSharedBundleList_.try_emplace(bundleName, baseSharedBundleInfoList);
4650 }
4651 
4652 void AppMgrServiceInner::RemoveRunningSharedBundleList(const std::string &bundleName)
4653 {
4654     auto iterator = runningSharedBundleList_.find(bundleName);
4655     if (iterator == runningSharedBundleList_.end()) {
4656         return;
4657     }
4658     runningSharedBundleList_.erase(iterator);
4659 }
4660 
4661 void AppMgrServiceInner::SetCurrentUserId(const int32_t userId)
4662 {
4663     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
4664         return;
4665     }
4666     HILOG_DEBUG("set current userId: %{public}d", userId);
4667     currentUserId_ = userId;
4668 }
4669 
4670 int32_t AppMgrServiceInner::GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid)
4671 {
4672     auto callerRecord = GetAppRunningRecordByPid(pid);
4673     if (callerRecord == nullptr) {
4674         HILOG_ERROR("callerRecord is nullptr, can not get callerBundleName.");
4675         return ERR_INVALID_OPERATION;
4676     }
4677     bundleName = callerRecord->GetBundleName();
4678     uid = callerRecord->GetUid();
4679     return ERR_OK;
4680 }
4681 void AppMgrServiceInner::KillRenderProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
4682     if (appRecord == nullptr) {
4683         HILOG_ERROR("appRecord is nullptr.");
4684         return;
4685     }
4686     auto renderRecordMap = appRecord->GetRenderRecordMap();
4687     if (!renderRecordMap.empty()) {
4688         for (auto iter : renderRecordMap) {
4689             auto renderRecord = iter.second;
4690             if (renderRecord && renderRecord->GetPid() > 0) {
4691                 HILOG_DEBUG("Kill render process when host died.");
4692                 KillProcessByPid(renderRecord->GetPid());
4693                 {
4694                     std::lock_guard lock(renderUidSetLock_);
4695                     renderUidSet_.erase(renderRecord->GetUid());
4696                 }
4697                 DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
4698             }
4699         }
4700     }
4701 }
4702 
4703 int32_t AppMgrServiceInner::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize)
4704 {
4705     CHECK_CALLER_IS_SYSTEM_APP;
4706     uint64_t memSize = OHOS::MemInfo::GetPssByPid(pid);
4707     memorySize = static_cast<int32_t>(memSize);
4708     return ERR_OK;
4709 }
4710 
4711 int32_t AppMgrServiceInner::GetRunningProcessInformation(
4712     const std::string &bundleName, int32_t userId, std::vector<RunningProcessInfo> &info)
4713 {
4714     CHECK_CALLER_IS_SYSTEM_APP;
4715     if (!appRunningManager_) {
4716         HILOG_ERROR("The appRunningManager is nullptr!");
4717         return ERR_NO_INIT;
4718     }
4719 
4720     if (remoteClientManager_ == nullptr) {
4721         HILOG_ERROR("The remoteClientManager_ is nullptr!");
4722         return ERR_NO_INIT;
4723     }
4724     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
4725     if (bundleMgrHelper == nullptr) {
4726         HILOG_ERROR("The bundleMgrHelper is nullptr!");
4727         return ERR_NO_INIT;
4728     }
4729     HILOG_INFO("userid value is %{public}d", userId);
4730     int uid = IN_PROCESS_CALL(bundleMgrHelper->GetUidByBundleName(bundleName, userId));
4731     HILOG_INFO("uid value is %{public}d", uid);
4732     const auto &appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
4733     for (const auto &item : appRunningRecordMap) {
4734         const auto &appRecord = item.second;
4735         if (appRecord == nullptr) {
4736             continue;
4737         }
4738         auto appInfoList = appRecord->GetAppInfoList();
4739         for (const auto &appInfo : appInfoList) {
4740             if (appInfo == nullptr) {
4741                 continue;
4742             }
4743             if (appInfo->bundleName == bundleName && appInfo->uid == uid) {
4744                 GetRunningProcesses(appRecord, info);
4745                 break;
4746             }
4747         }
4748     }
4749     return ERR_OK;
4750 }
4751 
4752 int32_t AppMgrServiceInner::ChangeAppGcState(pid_t pid, int32_t state)
4753 {
4754     HILOG_DEBUG("called, pid:%{public}d, state:%{public}d.", pid, state);
4755     auto appRecord = GetAppRunningRecordByPid(pid);
4756     if (!appRecord) {
4757         HILOG_ERROR("no such appRecord");
4758         return ERR_INVALID_VALUE;
4759     }
4760     return appRecord->ChangeAppGcState(state);
4761 }
4762 
4763 int32_t AppMgrServiceInner::RegisterAppDebugListener(const sptr<IAppDebugListener> &listener)
4764 {
4765     HILOG_DEBUG("Called.");
4766     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4767         HILOG_ERROR("Permission verification failed.");
4768         return ERR_PERMISSION_DENIED;
4769     }
4770 
4771     if (appDebugManager_ == nullptr) {
4772         HILOG_ERROR("appDebugManager_ is nullptr.");
4773         return ERR_NO_INIT;
4774     }
4775     return appDebugManager_->RegisterAppDebugListener(listener);
4776 }
4777 
4778 int32_t AppMgrServiceInner::UnregisterAppDebugListener(const sptr<IAppDebugListener> &listener)
4779 {
4780     HILOG_DEBUG("Called.");
4781     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4782         HILOG_ERROR("Permission verification failed.");
4783         return ERR_PERMISSION_DENIED;
4784     }
4785 
4786     if (appDebugManager_ == nullptr) {
4787         HILOG_ERROR("appDebugManager_ is nullptr.");
4788         return ERR_NO_INIT;
4789     }
4790     return appDebugManager_->UnregisterAppDebugListener(listener);
4791 }
4792 
4793 int32_t AppMgrServiceInner::AttachAppDebug(const std::string &bundleName)
4794 {
4795     HILOG_DEBUG("Called.");
4796     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
4797         HILOG_ERROR("Developer Mode is false.");
4798         return ERR_INVALID_OPERATION;
4799     }
4800 
4801     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
4802         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
4803         HILOG_ERROR("Permission verification failed.");
4804         return ERR_PERMISSION_DENIED;
4805     }
4806 
4807     if (appRunningManager_ == nullptr) {
4808         HILOG_ERROR("appRunningManager_ is nullptr.");
4809         return ERR_NO_INIT;
4810     }
4811     appRunningManager_->SetAttachAppDebug(bundleName, true);
4812 
4813     auto debugInfos = appRunningManager_->GetAppDebugInfosByBundleName(bundleName, false);
4814     if (!debugInfos.empty() && appDebugManager_ != nullptr) {
4815         appDebugManager_->StartDebug(debugInfos);
4816     }
4817 
4818     NotifyAbilitysDebugChange(bundleName, true);
4819     return ERR_OK;
4820 }
4821 
4822 int32_t AppMgrServiceInner::DetachAppDebug(const std::string &bundleName)
4823 {
4824     HILOG_DEBUG("Called.");
4825     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
4826         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
4827         HILOG_ERROR("Permission verification failed.");
4828         return ERR_PERMISSION_DENIED;
4829     }
4830 
4831     if (appRunningManager_ == nullptr) {
4832         HILOG_ERROR("appRunningManager_ is nullptr.");
4833         return ERR_NO_INIT;
4834     }
4835 
4836     auto debugInfos = appRunningManager_->GetAppDebugInfosByBundleName(bundleName, true);
4837     if (!debugInfos.empty()) {
4838         appRunningManager_->SetAttachAppDebug(bundleName, false);
4839         if (appDebugManager_ != nullptr) {
4840             appDebugManager_->StopDebug(debugInfos);
4841         }
4842     }
4843 
4844     NotifyAbilitysDebugChange(bundleName, false);
4845     return ERR_OK;
4846 }
4847 
4848 int32_t AppMgrServiceInner::RegisterAbilityDebugResponse(const sptr<IAbilityDebugResponse> &response)
4849 {
4850     if (response == nullptr) {
4851         HILOG_ERROR("Response is nullptr.");
4852         return ERR_INVALID_VALUE;
4853     }
4854 
4855     abilityDebugResponse_ = response;
4856     return ERR_OK;
4857 }
4858 
4859 int32_t AppMgrServiceInner::NotifyAbilitysDebugChange(const std::string &bundleName, const bool &isAppDebug)
4860 {
4861     if (appRunningManager_ == nullptr || abilityDebugResponse_ == nullptr) {
4862         HILOG_ERROR("appRunningManager_ or abilityDebugResponse is nullptr.");
4863         return ERR_NO_INIT;
4864     }
4865 
4866     std::vector<sptr<IRemoteObject>> tokens;
4867     appRunningManager_->GetAbilityTokensByBundleName(bundleName, tokens);
4868     if (!tokens.empty()) {
4869         isAppDebug ? abilityDebugResponse_->OnAbilitysDebugStarted(tokens) :
4870             abilityDebugResponse_->OnAbilitysDebugStoped(tokens);
4871     }
4872     return ERR_OK;
4873 }
4874 
4875 bool AppMgrServiceInner::IsAttachDebug(const std::string &bundleName)
4876 {
4877     HILOG_DEBUG("Called.");
4878     if (appRunningManager_ == nullptr || bundleName.empty()) {
4879         HILOG_ERROR("appRunningManager_ or bundleName is nullptr.");
4880         return false;
4881     }
4882     return appDebugManager_->IsAttachDebug(bundleName);
4883 }
4884 
4885 void AppMgrServiceInner::ApplicationTerminatedSendProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
4886 {
4887     if (appRecord == nullptr) {
4888         HILOG_ERROR("App record is nullptr.");
4889         return;
4890     }
4891 
4892     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
4893     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
4894         RemoveRunningSharedBundleList(appRecord->GetBundleName());
4895     }
4896 
4897     if (appRunningManager_ == nullptr) {
4898         HILOG_ERROR("App running manager is nullptr.");
4899         return;
4900     }
4901     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
4902         OnAppStopped(appRecord);
4903     }
4904 
4905     if (appDebugManager_ == nullptr) {
4906         HILOG_ERROR("App debug manager is nullptr.");
4907         return;
4908     }
4909     auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
4910     appDebugManager_->RemoveAppDebugInfo(info);
4911 
4912     HILOG_DEBUG("Application is terminated.");
4913     if (appRecord->GetPriorityObject() == nullptr) {
4914         HILOG_ERROR("Get priority object is nullptr.");
4915         return;
4916     }
4917     SendProcessExitEvent(appRecord->GetPriorityObject()->GetPid());
4918 }
4919 
4920 void AppMgrServiceInner::ClearAppRunningDataForKeepAlive(const std::shared_ptr<AppRunningRecord> &appRecord)
4921 {
4922     if (appRecord == nullptr) {
4923         HILOG_ERROR("App record is nullptr.");
4924         return;
4925     }
4926 
4927     if (appRecord->IsKeepAliveApp()) {
4928         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
4929             innerService->RestartResidentProcess(appRecord);
4930         };
4931         if (taskHandler_ == nullptr) {
4932             HILOG_ERROR("taskHandler_ is nullptr.");
4933             return;
4934         }
4935         if (appRecord->CanRestartResidentProc()) {
4936             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcess");
4937         } else {
4938             auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
4939                 return (appRecord != nullptr && appRunningRecord != nullptr &&
4940                         appRecord->GetBundleName() == appRunningRecord->GetBundleName());
4941             };
4942             auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(),
4943                 findRestartResidentTask);
4944             if (findIter != restartResedentTaskList_.end()) {
4945                 HILOG_WARN("The restart app task has been registered.");
4946                 return;
4947             }
4948             restartResedentTaskList_.emplace_back(appRecord);
4949             HILOG_DEBUG("Post restart resident process delay task.");
4950             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcessDelayTask", RESTART_INTERVAL_TIME);
4951         }
4952     }
4953 }
4954 
4955 int32_t AppMgrServiceInner::NotifyPageShow(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
4956 {
4957     if (!JudgeSelfCalledByToken(token, pageStateData)) {
4958         return ERR_PERMISSION_DENIED;
4959     }
4960 
4961     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnPageShow(pageStateData);
4962     return ERR_OK;
4963 }
4964 
4965 int32_t AppMgrServiceInner::NotifyPageHide(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
4966 {
4967     if (!JudgeSelfCalledByToken(token, pageStateData)) {
4968         return ERR_PERMISSION_DENIED;
4969     }
4970 
4971     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnPageHide(pageStateData);
4972     return ERR_OK;
4973 }
4974 
4975 bool AppMgrServiceInner::JudgeSelfCalledByToken(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
4976 {
4977     if (!token) {
4978         HILOG_ERROR("token is null.");
4979         return false;
4980     }
4981     auto appRecord = GetAppRunningRecordByAbilityToken(token);
4982     if (!appRecord) {
4983         HILOG_ERROR("app is not exist!");
4984         return false;
4985     }
4986     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
4987     if (appRecord->GetApplicationInfo() == nullptr ||
4988         ((appRecord->GetApplicationInfo())->accessTokenId) != callingTokenId) {
4989         HILOG_ERROR("Is not self, not enabled");
4990         return false;
4991     }
4992     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
4993     if (!abilityRecord) {
4994         HILOG_ERROR("can not find ability record");
4995         return false;
4996     }
4997     if (abilityRecord->GetBundleName() != pageStateData.bundleName ||
4998         abilityRecord->GetModuleName() != pageStateData.moduleName ||
4999         abilityRecord->GetName() != pageStateData.abilityName) {
5000         HILOG_ERROR("can not map the ability");
5001         return false;
5002     }
5003     return true;
5004 }
5005 
5006 void AppMgrServiceInner::SendReStartProcessEvent(const AAFwk::EventInfo &eventInfo,
5007     const std::shared_ptr<AppRunningRecord> &appRecord)
5008 {
5009     HILOG_DEBUG("Called.");
5010     if (!appRecord) {
5011         HILOG_ERROR("appRecord is nullptr");
5012         return;
5013     }
5014     std::lock_guard<ffrt::mutex> lock(killpedProcessMapLock_);
5015     int64_t restartTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
5016         system_clock::now().time_since_epoch()).count();
5017     for (auto iter = killedPorcessMap_.begin(); iter != killedPorcessMap_.end();) {
5018         int64_t killTime = iter->first;
5019         if (restartTime - killTime > 2000) {
5020             killedPorcessMap_.erase(iter++);
5021             continue;
5022         }
5023         AAFwk::EventInfo currentEventInfo;
5024         currentEventInfo = eventInfo;
5025         currentEventInfo.time = restartTime;
5026         std::string processName = appRecord->GetProcessName();
5027         currentEventInfo.appUid = appRecord->GetUid();
5028         if (currentEventInfo.bundleName == currentEventInfo.callerBundleName &&
5029             processName != currentEventInfo.callerProcessName) {
5030             currentEventInfo.processName = processName;
5031             AAFwk::EventReport::SendKeyEvent(AAFwk::EventName::RESTART_PROCESS_BY_SAME_APP,
5032                 HiSysEventType::BEHAVIOR, eventInfo);
5033             killedPorcessMap_.erase(iter++);
5034             continue;
5035         }
5036         iter++;
5037     }
5038 }
5039 
5040 int32_t AppMgrServiceInner::RegisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
5041 {
5042     HILOG_DEBUG("Call.");
5043     CHECK_IS_SA_CALL(listener);
5044     auto appRunningStatusListener = iface_cast<AbilityRuntime::AppRunningStatusListenerInterface>(listener);
5045     return appRunningStatusModule_->RegisterListener(appRunningStatusListener);
5046 }
5047 
5048 int32_t AppMgrServiceInner::UnregisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
5049 {
5050     HILOG_DEBUG("Call.");
5051     CHECK_IS_SA_CALL(listener);
5052     auto appRunningStatusListener = iface_cast<AbilityRuntime::AppRunningStatusListenerInterface>(listener);
5053     return appRunningStatusModule_->UnregisterListener(appRunningStatusListener);
5054 }
5055 
5056 int32_t AppMgrServiceInner::StartChildProcess(const pid_t hostPid, const std::string &srcEntry, pid_t &childPid)
5057 {
5058     HILOG_INFO("StarChildProcess, hostPid:%{public}d", hostPid);
5059     auto errCode = StartChildProcessPreCheck(hostPid);
5060     if (errCode != ERR_OK) {
5061         return errCode;
5062     }
5063     if (hostPid <= 0 || srcEntry.empty()) {
5064         HILOG_ERROR("Invalid param: hostPid:%{public}d srcEntry:%{private}s", hostPid, srcEntry.c_str());
5065         return ERR_INVALID_VALUE;
5066     }
5067     if (!appRunningManager_) {
5068         HILOG_ERROR("appRunningManager_ is null");
5069         return ERR_NO_INIT;
5070     }
5071     auto appRecord = GetAppRunningRecordByPid(hostPid);
5072     auto childProcessRecord = ChildProcessRecord::CreateChildProcessRecord(hostPid, srcEntry, appRecord);
5073     return StartChildProcessImpl(childProcessRecord, appRecord, childPid);
5074 }
5075 
5076 int32_t AppMgrServiceInner::StartChildProcessPreCheck(const pid_t callingPid)
5077 {
5078     if (!AAFwk::AppUtils::GetInstance().isMultiProcessModel()) {
5079         HILOG_ERROR("Multi process model is not enabled");
5080         return ERR_INVALID_OPERATION;
5081     }
5082     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(callingPid);
5083     if (appRecord) {
5084         HILOG_ERROR("Already in child process.");
5085         return ERR_ALREADY_EXISTS;
5086     }
5087     return ERR_OK;
5088 }
5089 
5090 int32_t AppMgrServiceInner::StartChildProcessImpl(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
5091     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &childPid)
5092 {
5093     HILOG_DEBUG("Called.");
5094     if (!appRecord) {
5095         HILOG_ERROR("No such appRecord, childPid:%{public}d.", childPid);
5096         return ERR_NAME_NOT_FOUND;
5097     }
5098     if (!childProcessRecord) {
5099         HILOG_ERROR("No such child process record, childPid:%{public}d.", childPid);
5100         return ERR_NAME_NOT_FOUND;
5101     }
5102     auto spawnClient = remoteClientManager_->GetSpawnClient();
5103     if (!spawnClient) {
5104         HILOG_ERROR("spawnClient is null");
5105         return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
5106     }
5107 
5108     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
5109     startMsg.procName = childProcessRecord->GetProcessName();
5110     pid_t pid = 0;
5111     ErrCode errCode = spawnClient->StartProcess(startMsg, pid);
5112     if (FAILED(errCode)) {
5113         HILOG_ERROR("failed to spawn new child process, errCode %{public}08x", errCode);
5114         return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
5115     }
5116 
5117     childPid = pid;
5118     childProcessRecord->SetPid(pid);
5119     childProcessRecord->SetUid(startMsg.uid);
5120     appRecord->AddChildProcessRecord(pid, childProcessRecord);
5121     HILOG_INFO("Start child process success, pid:%{public}d, uid:%{public}d", pid, startMsg.uid);
5122     return ERR_OK;
5123 }
5124 
5125 int32_t AppMgrServiceInner::GetChildProcessInfoForSelf(ChildProcessInfo &info)
5126 {
5127     HILOG_DEBUG("Called.");
5128     if (!appRunningManager_) {
5129         HILOG_ERROR("appRunningManager_ is null");
5130         return ERR_NO_INIT;
5131     }
5132     auto callingPid = IPCSkeleton::GetCallingPid();
5133     if (appRunningManager_->GetAppRunningRecordByPid(callingPid)) {
5134         HILOG_DEBUG("record of callingPid is not child record.");
5135         return ERR_NAME_NOT_FOUND;
5136     }
5137     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(callingPid);
5138     if (!appRecord) {
5139         HILOG_WARN("No such appRecord, childPid:%{public}d", callingPid);
5140         return ERR_NAME_NOT_FOUND;
5141     }
5142     auto childRecordMap = appRecord->GetChildProcessRecordMap();
5143     auto iter = childRecordMap.find(callingPid);
5144     if (iter != childRecordMap.end()) {
5145         auto childProcessRecord = iter->second;
5146         return GetChildProcessInfo(childProcessRecord, appRecord, info);
5147     }
5148     return ERR_NAME_NOT_FOUND;
5149 }
5150 
5151 int32_t AppMgrServiceInner::GetChildProcessInfo(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
5152     const std::shared_ptr<AppRunningRecord> appRecord, ChildProcessInfo &info)
5153 {
5154     HILOG_DEBUG("Called.");
5155     if (!childProcessRecord) {
5156         HILOG_ERROR("No such child process record.");
5157         return ERR_NAME_NOT_FOUND;
5158     }
5159     if (!appRecord) {
5160         HILOG_ERROR("No such appRecord.");
5161         return ERR_NAME_NOT_FOUND;
5162     }
5163     info.pid = childProcessRecord->GetPid();
5164     info.hostPid = childProcessRecord->GetHostPid();
5165     info.uid = childProcessRecord->GetUid();
5166     info.bundleName = appRecord->GetBundleName();
5167     info.processName = childProcessRecord->GetProcessName();
5168     info.srcEntry = childProcessRecord->GetSrcEntry();
5169     return ERR_OK;
5170 }
5171 
5172 void AppMgrServiceInner::AttachChildProcess(const pid_t pid, const sptr<IChildScheduler> &childScheduler)
5173 {
5174     HILOG_INFO("AttachChildProcess pid:%{public}d", pid);
5175     if (pid <= 0) {
5176         HILOG_ERROR("invalid child process pid:%{public}d", pid);
5177         return;
5178     }
5179     if (!childScheduler) {
5180         HILOG_ERROR("childScheduler is null");
5181         return;
5182     }
5183     if (!appRunningManager_) {
5184         HILOG_ERROR("appRunningManager_ is null");
5185         return;
5186     }
5187     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
5188     if (!appRecord) {
5189         HILOG_ERROR("no such app Record, pid:%{public}d", pid);
5190         return;
5191     }
5192     auto childRecord = appRecord->GetChildProcessRecordByPid(pid);
5193     if (!childRecord) {
5194         HILOG_ERROR("no such child process Record, pid:%{public}d", pid);
5195         return;
5196     }
5197 
5198     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
5199     appDeathRecipient->SetTaskHandler(taskHandler_);
5200     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
5201     appDeathRecipient->SetIsChildProcess(true);
5202     childRecord->SetScheduler(childScheduler);
5203     childRecord->SetDeathRecipient(appDeathRecipient);
5204     childRecord->RegisterDeathRecipient();
5205 
5206     childScheduler->ScheduleLoadJs();
5207 }
5208 
5209 void AppMgrServiceInner::OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote)
5210 {
5211     if (appRunningManager_) {
5212         appRunningManager_->OnChildProcessRemoteDied(remote);
5213     }
5214 }
5215 
5216 void AppMgrServiceInner::KillChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
5217     if (appRecord == nullptr) {
5218         HILOG_ERROR("appRecord is nullptr.");
5219         return;
5220     }
5221     auto childRecordMap = appRecord->GetChildProcessRecordMap();
5222     if (childRecordMap.empty()) {
5223         return;
5224     }
5225     for (auto iter : childRecordMap) {
5226         auto childRecord = iter.second;
5227         if (childRecord && childRecord->GetPid() > 0) {
5228             HILOG_DEBUG("Kill child process when host died.");
5229             KillProcessByPid(childRecord->GetPid());
5230         }
5231     }
5232 }
5233 
5234 void AppMgrServiceInner::ExitChildProcessSafelyByChildPid(const pid_t pid)
5235 {
5236     if (pid <= 0) {
5237         HILOG_ERROR("pid <= 0.");
5238         return;
5239     }
5240     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
5241     if (!appRecord) {
5242         HILOG_ERROR("no such app Record, pid:%{public}d", pid);
5243         return;
5244     }
5245     auto childRecord = appRecord->GetChildProcessRecordByPid(pid);
5246     if (!childRecord) {
5247         HILOG_ERROR("no such child process Record, pid:%{public}d", pid);
5248         return;
5249     }
5250     childRecord->ScheduleExitProcessSafely();
5251     childRecord->RemoveDeathRecipient();
5252     int64_t startTime = SystemTimeMillisecond();
5253     std::list<pid_t> pids;
5254     pids.push_back(pid);
5255     if (WaitForRemoteProcessExit(pids, startTime)) {
5256         HILOG_INFO("The remote child process exited successfully, pid:%{public}d.", pid);
5257         appRecord->RemoveChildProcessRecord(childRecord);
5258         return;
5259     }
5260     childRecord->RegisterDeathRecipient();
5261     int32_t result = KillProcessByPid(pid);
5262     if (result < 0) {
5263         HILOG_ERROR("KillChildProcessByPid kill process is fail.");
5264         return;
5265     }
5266 }
5267 
5268 void AppMgrServiceInner::NotifyAppRunningStatusEvent(
5269     const std::string &bundle, int32_t uid, AbilityRuntime::RunningStatus runningStatus)
5270 {
5271     if (appRunningStatusModule_ == nullptr) {
5272         HILOG_ERROR("Get app running status module object is nullptr.");
5273         return;
5274     }
5275     appRunningStatusModule_->NotifyAppRunningStatusEvent(bundle, uid, runningStatus);
5276 }
5277 
5278 void AppMgrServiceInner::SendAppLaunchEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
5279 {
5280     if (!appRecord) {
5281         HILOG_ERROR("appRecord is null");
5282         return;
5283     }
5284     AAFwk::EventInfo eventInfo;
5285     auto applicationInfo = appRecord->GetApplicationInfo();
5286     if (!applicationInfo) {
5287         HILOG_ERROR("applicationInfo is nullptr");
5288     } else {
5289         eventInfo.bundleName = applicationInfo->name;
5290         eventInfo.versionName = applicationInfo->versionName;
5291         eventInfo.versionCode = applicationInfo->versionCode;
5292     }
5293     if (appRecord->GetPriorityObject() != nullptr) {
5294         eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
5295     }
5296     eventInfo.processName = appRecord->GetProcessName();
5297     int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
5298     auto callerRecord = GetAppRunningRecordByPid(callerPid);
5299     if (callerRecord != nullptr) {
5300         eventInfo.callerBundleName = callerRecord->GetBundleName();
5301         eventInfo.callerUid = callerRecord->GetUid();
5302         eventInfo.callerState = static_cast<int32_t>(callerRecord->GetState());
5303         auto callerApplicationInfo = callerRecord->GetApplicationInfo();
5304         if (callerApplicationInfo != nullptr) {
5305             eventInfo.callerVersionName = callerApplicationInfo->versionName;
5306             eventInfo.callerVersionCode = callerApplicationInfo->versionCode;
5307         }
5308     } else {
5309         HILOG_ERROR("callerRecord is nullptr, can not get callerBundleName.");
5310     }
5311     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_LAUNCH, HiSysEventType::BEHAVIOR, eventInfo);
5312 }
5313 
5314 bool AppMgrServiceInner::IsFinalAppProcessByBundleName(const std::string &bundleName)
5315 {
5316     if (appRunningManager_ == nullptr) {
5317         HILOG_ERROR("App running manager is nullptr.");
5318         return false;
5319     }
5320 
5321     auto name = bundleName;
5322     if (bundleName.empty()) {
5323         auto callingPid = IPCSkeleton::GetCallingPid();
5324         auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callingPid);
5325         if (appRecord == nullptr) {
5326             HILOG_ERROR("Get app running record is nullptr.");
5327             return false;
5328         }
5329         name = appRecord->GetBundleName();
5330     }
5331 
5332     auto count = appRunningManager_->GetAllAppRunningRecordCountByBundleName(name);
5333     HILOG_DEBUG("Get application %{public}s process list size[%{public}d].", name.c_str(), count);
5334     return count == 1;
5335 }
5336 
5337 void AppMgrServiceInner::ParseServiceExtMultiProcessWhiteList()
5338 {
5339     auto serviceExtMultiProcessWhiteList =
5340         OHOS::system::GetParameter(SERVICE_EXT_MULTI_PROCESS_WHITE_LIST, "");
5341     if (serviceExtMultiProcessWhiteList.empty()) {
5342         HILOG_WARN("Service extension multi process white list is empty.");
5343         return;
5344     }
5345     SplitStr(serviceExtMultiProcessWhiteList, ";", serviceExtensionWhiteList_);
5346 }
5347 
5348 void AppMgrServiceInner::ClearProcessByToken(sptr<IRemoteObject> token)
5349 {
5350     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
5351     if (token == nullptr) {
5352         HILOG_ERROR("token is null");
5353         return;
5354     }
5355 
5356     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
5357     {
5358         std::lock_guard lock(exceptionLock_);
5359         appRecord = GetAppRunningRecordByAbilityToken(token);
5360         if (appRecord == nullptr) {
5361             HILOG_INFO("app record is not exist for ability token");
5362             return;
5363         }
5364         appRecord->SetApplicationClient(nullptr);
5365         auto recordId = appRecord->GetRecordId();
5366         if (appRunningManager_ == nullptr) {
5367             HILOG_ERROR("appRunningManager_ is nullptr");
5368             return;
5369         }
5370         appRunningManager_->RemoveAppRunningRecordById(recordId);
5371     }
5372     ClearData(appRecord);
5373 }
5374 
5375 void AppMgrServiceInner::ClearData(std::shared_ptr<AppRunningRecord> appRecord)
5376 {
5377     if (appRecord == nullptr) {
5378         HILOG_WARN("app record is nullptr.");
5379         return;
5380     }
5381     ClearAppRunningData(appRecord, false);
5382     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
5383         RemoveRunningSharedBundleList(appRecord->GetBundleName());
5384     }
5385 }
5386 }  // namespace AppExecFwk
5387 }  // namespace OHOS
5388