• 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 "accesstoken_kit.h"
27 #include "app_mem_info.h"
28 #include "app_mgr_service.h"
29 #include "app_process_data.h"
30 #include "app_state_observer_manager.h"
31 #include "appfreeze_manager.h"
32 #include "application_state_observer_stub.h"
33 #include "appspawn_mount_permission.h"
34 #include "bundle_constants.h"
35 #include "common_event.h"
36 #include "common_event_manager.h"
37 #include "common_event_support.h"
38 #include "datetime_ex.h"
39 #include "event_report.h"
40 #include "hilog_wrapper.h"
41 #include "hisysevent.h"
42 #include "hitrace_meter.h"
43 #include "in_process_call_wrapper.h"
44 #include "ipc_skeleton.h"
45 #include "iremote_object.h"
46 #include "iservice_registry.h"
47 #include "itest_observer.h"
48 #ifdef SUPPORT_GRAPHICS
49 #include "locale_config.h"
50 #endif
51 #include "os_account_manager_wrapper.h"
52 #include "parameter.h"
53 #include "parameters.h"
54 #include "perf_profile.h"
55 #include "permission_constants.h"
56 #include "permission_verification.h"
57 #include "system_ability_definition.h"
58 #include "ui_extension_utils.h"
59 #include "uri_permission_manager_client.h"
60 #ifdef APP_MGR_SERVICE_APPMS
61 #include "socket_permission.h"
62 #endif
63 #include "application_info.h"
64 #include "meminfo.h"
65 
66 namespace OHOS {
67 namespace AppExecFwk {
68 using namespace OHOS::Rosen;
69 using namespace OHOS::Security;
70 
71 namespace {
72 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
73     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
74         HILOG_ERROR("The caller is not system-app, can not use system-api");                   \
75         return AAFwk::ERR_NOT_SYSTEM_APP;                                                             \
76     }
77 
78 // NANOSECONDS mean 10^9 nano second
79 constexpr int64_t NANOSECONDS = 1000000000;
80 // MICROSECONDS mean 10^6 milli second
81 constexpr int64_t MICROSECONDS = 1000000;
82 // Kill process timeout setting
83 constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000;
84 // Kill process delay time setting
85 constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200;
86 // delay register focus listener to wms
87 constexpr int REGISTER_FOCUS_DELAY = 5000;
88 const std::string CLASS_NAME = "ohos.app.MainThread";
89 const std::string FUNC_NAME = "main";
90 const std::string RENDER_PARAM = "invalidparam";
91 const std::string COLD_START = "coldStart";
92 const std::string PERF_CMD = "perfCmd";
93 const std::string DEBUG_CMD = "debugCmd";
94 const std::string ENTER_SANBOX = "sanboxApp";
95 const std::string DLP_PARAMS_INDEX = "ohos.dlp.params.index";
96 const std::string PERMISSION_INTERNET = "ohos.permission.INTERNET";
97 const std::string PERMISSION_MANAGE_VPN = "ohos.permission.MANAGE_VPN";
98 const std::string PERMISSION_ACCESS_BUNDLE_DIR = "ohos.permission.ACCESS_BUNDLE_DIR";
99 const std::string DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
100 const std::string SUPPORT_ISOLATION_MODE = "persist.bms.supportIsolationMode";
101 const std::string SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard";
102 const int32_t SIGNAL_KILL = 9;
103 constexpr int32_t USER_SCALE = 200000;
104 #define ENUM_TO_STRING(s) #s
105 #define APP_ACCESS_BUNDLE_DIR 0x20
106 #define APP_OVERLAY_FLAG 0x100
107 
108 constexpr int32_t BASE_USER_RANGE = 200000;
109 
110 constexpr int32_t MAX_RESTART_COUNT = 3;
111 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
112 
113 constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01);
114 constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100; // error code for already exist render.
115 constexpr char EVENT_KEY_UID[] = "UID";
116 constexpr char EVENT_KEY_PID[] = "PID";
117 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
118 constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME";
119 constexpr char EVENT_KEY_MESSAGE[] = "MSG";
120 
121 // Msg length is less than 48 characters
122 const std::string EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!";
123 const std::string EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!";
124 const std::string EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT = "Add Ability Stage TimeOut!";
125 const std::string EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!";
126 const std::string EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = "Start Process Specified Ability TimeOut!";
127 const std::string EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!";
128 
129 const std::string SYSTEM_BASIC = "system_basic";
130 const std::string SYSTEM_CORE = "system_core";
131 const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
132 const std::string PROCESS_EXIT_EVENT_TASK = "Send Process Exit Event Task";
133 
134 constexpr int32_t ROOT_UID = 0;
135 constexpr int32_t FOUNDATION_UID = 5523;
136 constexpr int32_t QUICKFIX_UID = 5524;
137 constexpr int32_t DEFAULT_USER_ID = 0;
138 
139 constexpr int32_t BLUETOOTH_GROUPID = 1002;
140 
141 #ifdef APP_MGR_SERVICE_APPMS
142 constexpr int32_t NETSYS_SOCKET_GROUPID = 1097;
143 #endif
144 
GetUserIdByUid(int32_t uid)145 int32_t GetUserIdByUid(int32_t uid)
146 {
147     return uid / BASE_USER_RANGE;
148 }
149 }  // namespace
150 
151 using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED;
152 using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
153 
AppMgrServiceInner()154 AppMgrServiceInner::AppMgrServiceInner()
155     : appProcessManager_(std::make_shared<AppProcessManager>()),
156       remoteClientManager_(std::make_shared<RemoteClientManager>()),
157       appRunningManager_(std::make_shared<AppRunningManager>()),
158       configuration_(std::make_shared<Configuration>())
159 {}
160 
Init()161 void AppMgrServiceInner::Init()
162 {
163     InitGlobalConfiguration();
164     AddWatchParameter();
165     supportIsolationMode_ = OHOS::system::GetParameter(SUPPORT_ISOLATION_MODE, "false");
166     deviceType_ = OHOS::system::GetDeviceType();
167     DelayedSingleton<AppStateObserverManager>::GetInstance()->Init();
168     InitFocusListener();
169 }
170 
~AppMgrServiceInner()171 AppMgrServiceInner::~AppMgrServiceInner()
172 {}
173 
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)174 void AppMgrServiceInner::LoadAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
175     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
176     const std::shared_ptr<AAFwk::Want> &want)
177 {
178     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
179     if (!CheckLoadAbilityConditions(token, abilityInfo, appInfo)) {
180         HILOG_ERROR("CheckLoadAbilityConditions failed");
181         return;
182     }
183     HILOG_INFO("load,name:%{public}s.", abilityInfo->name.c_str());
184 
185     if (!appRunningManager_) {
186         HILOG_ERROR("appRunningManager_ is nullptr");
187         return;
188     }
189 
190     BundleInfo bundleInfo;
191     HapModuleInfo hapModuleInfo;
192     int32_t appIndex = (want == nullptr) ? 0 : want->GetIntParam(DLP_PARAMS_INDEX, 0);
193     if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
194         HILOG_ERROR("GetBundleAndHapInfo failed");
195         return;
196     }
197 
198     std::string processName;
199     MakeProcessName(abilityInfo, appInfo, hapModuleInfo, appIndex, processName);
200 
201     auto appRecord =
202         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
203     if (!appRecord) {
204         bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
205         appRecord = CreateAppRunningRecord(token, preToken, appInfo, abilityInfo,
206             processName, bundleInfo, hapModuleInfo, want);
207         if (!appRecord) {
208             HILOG_ERROR("CreateAppRunningRecord failed, appRecord is nullptr");
209             return;
210         }
211         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::COLD);
212         auto callRecord = GetAppRunningRecordByAbilityToken(preToken);
213         if (callRecord != nullptr) {
214             auto launchReson = (want == nullptr) ? 0 : want->GetIntParam("ohos.ability.launch.reason", 0);
215             HILOG_DEBUG("req: %{public}d, proc: %{public}s, call:%{public}d,%{public}s", launchReson,
216                 appInfo->name.c_str(), appRecord->GetCallerPid(), callRecord->GetBundleName().c_str());
217         }
218         uint32_t startFlags = (want == nullptr) ? 0 : BuildStartFlags(*want, *abilityInfo);
219         int32_t bundleIndex = (want == nullptr) ? 0 : want->GetIntParam(DLP_PARAMS_INDEX, 0);
220         StartProcess(abilityInfo->applicationName, processName, startFlags, appRecord,
221             appInfo->uid, appInfo->bundleName, bundleIndex, appExistFlag);
222         std::string perfCmd = (want == nullptr) ? "" : want->GetStringParam(PERF_CMD);
223         bool isSanboxApp = (want == nullptr) ? false : want->GetBoolParam(ENTER_SANBOX, false);
224         (void)StartPerfProcess(appRecord, perfCmd, "", isSanboxApp);
225     } else {
226         int32_t requestProcCode = (want == nullptr) ? 0 : want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0);
227         if (requestProcCode != 0 && appRecord->GetRequestProcCode() == 0) {
228             appRecord->SetRequestProcCode(requestProcCode);
229             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessReused(appRecord);
230         }
231         StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want);
232     }
233     PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
234     PerfProfile::GetInstance().Dump();
235     PerfProfile::GetInstance().Reset();
236 }
237 
CheckLoadAbilityConditions(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo)238 bool AppMgrServiceInner::CheckLoadAbilityConditions(const sptr<IRemoteObject> &token,
239     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo)
240 {
241     if (!token || !abilityInfo || !appInfo) {
242         HILOG_ERROR("param error");
243         return false;
244     }
245     if (abilityInfo->name.empty() || appInfo->name.empty()) {
246         HILOG_ERROR("error abilityInfo or appInfo");
247         return false;
248     }
249     if (abilityInfo->applicationName != appInfo->name) {
250         HILOG_ERROR("abilityInfo and appInfo have different appName, don't load for it");
251         return false;
252     }
253 
254     return true;
255 }
256 
MakeProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,int32_t appIndex,std::string & processName) const257 void AppMgrServiceInner::MakeProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
258     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, int32_t appIndex,
259     std::string &processName) const
260 {
261     if (!abilityInfo || !appInfo) {
262         HILOG_ERROR("param error");
263         return;
264     }
265     if (!abilityInfo->process.empty()) {
266         processName = abilityInfo->process;
267         return;
268     }
269     MakeProcessName(appInfo, hapModuleInfo, processName);
270     if (appIndex != 0) {
271         processName += std::to_string(appIndex);
272     }
273 }
274 
MakeProcessName(const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,std::string & processName) const275 void AppMgrServiceInner::MakeProcessName(
276     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, std::string &processName) const
277 {
278     if (!appInfo) {
279         return;
280     }
281     // check after abilityInfo, because abilityInfo contains extension process.
282     if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()
283         && hapModuleInfo.process != appInfo->bundleName) {
284         processName = hapModuleInfo.process;
285         HILOG_DEBUG("Stage mode, Make processName:%{public}s", processName.c_str());
286         return;
287     }
288     bool isRunInIsolationMode = CheckIsolationMode(hapModuleInfo);
289     if (hapModuleInfo.isStageBasedModel && isRunInIsolationMode) {
290         processName = appInfo->bundleName;
291         processName.append(":");
292         processName.append(hapModuleInfo.name);
293         return;
294     }
295     if (!appInfo->process.empty()) {
296         processName = appInfo->process;
297         return;
298     }
299     processName = appInfo->bundleName;
300 }
301 
CheckIsolationMode(const HapModuleInfo & hapModuleInfo) const302 bool AppMgrServiceInner::CheckIsolationMode(const HapModuleInfo &hapModuleInfo) const
303 {
304     IsolationMode isolationMode = hapModuleInfo.isolationMode;
305     if (supportIsolationMode_.compare("true") == 0) {
306         switch (isolationMode) {
307             case IsolationMode::ISOLATION_FIRST:
308                 return true;
309             case IsolationMode::ISOLATION_ONLY:
310                 return true;
311             default:
312                 return false;
313         }
314     }
315     return false;
316 }
317 
GetBundleAndHapInfo(const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo,int32_t appIndex) const318 bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo,
319     const std::shared_ptr<ApplicationInfo> &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo,
320     int32_t appIndex) const
321 {
322     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
323     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
324     if (bundleMgr_ == nullptr) {
325         HILOG_ERROR("GetBundleManager fail");
326         return false;
327     }
328 
329     auto userId = GetUserIdByUid(appInfo->uid);
330     HILOG_INFO("userId:%{public}d", userId);
331     bool bundleMgrResult;
332     if (appIndex == 0) {
333         bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfo(appInfo->bundleName,
334             BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
335     } else {
336         bundleMgrResult = (IN_PROCESS_CALL(bundleMgr_->GetSandboxBundleInfo(appInfo->bundleName,
337             appIndex, userId, bundleInfo)) == 0);
338     }
339 
340     if (!bundleMgrResult) {
341         HILOG_ERROR("GetBundleInfo is fail");
342         return false;
343     }
344     if (appIndex == 0) {
345         bundleMgrResult = bundleMgr_->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo);
346     } else {
347         bundleMgrResult = (bundleMgr_->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0);
348     }
349     if (!bundleMgrResult) {
350         HILOG_ERROR("GetHapModuleInfo is fail");
351         return false;
352     }
353 
354     return true;
355 }
356 
AttachApplication(const pid_t pid,const sptr<IAppScheduler> & appScheduler)357 void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &appScheduler)
358 {
359     if (pid <= 0) {
360         HILOG_ERROR("invalid pid:%{public}d", pid);
361         return;
362     }
363     auto appRecord = GetAppRunningRecordByPid(pid);
364     if (!appRecord) {
365         HILOG_ERROR("no such appRecord");
366         return;
367     }
368     auto applicationInfo = appRecord->GetApplicationInfo();
369     AAFwk::EventInfo eventInfo;
370     if (!applicationInfo) {
371         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
372     } else {
373         eventInfo.bundleName = applicationInfo->name;
374         eventInfo.versionName = applicationInfo->versionName;
375         eventInfo.versionCode = applicationInfo->versionCode;
376     }
377     std::string connector = "##";
378     std::string traceName = __PRETTY_FUNCTION__ + connector + eventInfo.bundleName;
379     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
380     if (!appScheduler) {
381         HILOG_ERROR("app client is null");
382         return;
383     }
384     HILOG_INFO("attach, pid:%{public}d.", pid);
385     appRecord->SetApplicationClient(appScheduler);
386     appRecord->RegisterAppDeathRecipient();
387     if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
388         LaunchApplication(appRecord);
389     }
390     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
391     eventInfo.processName = appRecord->GetProcessName();
392     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_ATTACH, HiSysEventType::BEHAVIOR, eventInfo);
393 }
394 
LaunchApplication(const std::shared_ptr<AppRunningRecord> & appRecord)395 void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
396 {
397     if (!appRecord) {
398         HILOG_ERROR("appRecord is null");
399         return;
400     }
401     AAFwk::EventInfo eventInfo;
402     auto applicationInfo = appRecord->GetApplicationInfo();
403     if (!applicationInfo) {
404         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
405     } else {
406         eventInfo.bundleName = applicationInfo->name;
407         eventInfo.versionName = applicationInfo->versionName;
408         eventInfo.versionCode = applicationInfo->versionCode;
409     }
410     std::string connector = "##";
411     std::string traceName = __PRETTY_FUNCTION__ + connector + eventInfo.bundleName;
412     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
413 
414     if (!configuration_) {
415         HILOG_ERROR("configuration_ is null");
416         return;
417     }
418 
419     if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
420         HILOG_ERROR("wrong app state:%{public}d", appRecord->GetState());
421         return;
422     }
423 
424     appRecord->LaunchApplication(*configuration_);
425     appRecord->SetState(ApplicationState::APP_STATE_READY);
426     int restartResidentProcCount = MAX_RESTART_COUNT;
427     appRecord->SetRestartResidentProcCount(restartResidentProcCount);
428 
429     // There is no ability when the empty resident process starts
430     // The status of all resident processes is ready
431     // There is no process of switching the foreground, waiting for his first ability to start
432     if (appRecord->IsEmptyKeepAliveApp()) {
433         appRecord->AddAbilityStage();
434         return;
435     }
436 
437     if (appRecord->IsStartSpecifiedAbility()) {
438         appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
439         return;
440     }
441     appRecord->LaunchPendingAbilities();
442     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
443     eventInfo.processName = appRecord->GetProcessName();
444     int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
445     auto callerRecord = GetAppRunningRecordByPid(callerPid);
446     if (callerRecord != nullptr) {
447         eventInfo.callerBundleName = callerRecord->GetBundleName();
448     } else {
449         HILOG_ERROR("callerRecord is nullptr, can not get callerBundleName.");
450     }
451     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_LAUNCH, HiSysEventType::BEHAVIOR, eventInfo);
452 }
453 
AddAbilityStageDone(const int32_t recordId)454 void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId)
455 {
456     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
457     if (!appRecord) {
458         HILOG_ERROR("get app record failed");
459         return;
460     }
461     appRecord->AddAbilityStageDone();
462 }
463 
ApplicationForegrounded(const int32_t recordId)464 void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId)
465 {
466     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
467     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
468     if (!appRecord || !appRecord->IsUpdateStateFromService()) {
469         HILOG_ERROR("get app record failed");
470         return;
471     }
472     appRecord->PopForegroundingAbilityTokens();
473     ApplicationState appState = appRecord->GetState();
474     if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) {
475         appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND);
476         bool needNotifyApp = appRunningManager_->IsApplicationFirstForeground(*appRecord);
477         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp);
478         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
479     } else {
480         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
481             appRecord->GetName().c_str(), static_cast<ApplicationState>(appState));
482     }
483     appRecord->SetUpdateStateFromService(false);
484 
485     // push the foregrounded app front of RecentAppList.
486     PushAppFront(recordId);
487     HILOG_INFO("application is foregrounded");
488     AAFwk::EventInfo eventInfo;
489     auto applicationInfo = appRecord->GetApplicationInfo();
490     if (!applicationInfo) {
491         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
492     } else {
493         eventInfo.bundleName = applicationInfo->name;
494         eventInfo.versionName = applicationInfo->versionName;
495         eventInfo.versionCode = applicationInfo->versionCode;
496         eventInfo.bundleType = static_cast<int32_t>(applicationInfo->bundleType);
497     }
498     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
499     eventInfo.processName = appRecord->GetProcessName();
500     int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
501     auto callerRecord = GetAppRunningRecordByPid(callerPid);
502     if (callerRecord != nullptr) {
503         eventInfo.callerBundleName = callerRecord->GetBundleName();
504     } else {
505         HILOG_ERROR("callerRecord is nullptr, can not get callerBundleName.");
506     }
507     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_FOREGROUND, HiSysEventType::BEHAVIOR, eventInfo);
508 }
509 
ApplicationBackgrounded(const int32_t recordId)510 void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId)
511 {
512     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
513     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
514     if (!appRecord || !appRecord->IsUpdateStateFromService()) {
515         HILOG_ERROR("get app record failed");
516         return;
517     }
518     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
519         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
520         bool needNotifyApp = !AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
521             && !AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
522             && appRunningManager_->IsApplicationBackground(appRecord->GetBundleName());
523         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND, needNotifyApp);
524         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
525     } else {
526         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
527             appRecord->GetName().c_str(), static_cast<ApplicationState>(appRecord->GetState()));
528     }
529     appRecord->SetUpdateStateFromService(false);
530 
531     HILOG_INFO("application is backgrounded");
532     AAFwk::EventInfo eventInfo;
533     auto applicationInfo = appRecord->GetApplicationInfo();
534     if (!applicationInfo) {
535         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
536     } else {
537         eventInfo.bundleName = applicationInfo->name;
538         eventInfo.versionName = applicationInfo->versionName;
539         eventInfo.versionCode = applicationInfo->versionCode;
540         eventInfo.bundleType = static_cast<int32_t>(applicationInfo->bundleType);
541     }
542     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
543     eventInfo.processName = appRecord->GetProcessName();
544     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_BACKGROUND, HiSysEventType::BEHAVIOR, eventInfo);
545 }
546 
ApplicationTerminated(const int32_t recordId)547 void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
548 {
549     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
550     if (!appRunningManager_) {
551         HILOG_ERROR("appRunningManager_ is nullptr");
552         return;
553     }
554 
555     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
556     if (!appRecord) {
557         HILOG_ERROR("get app record failed");
558         return;
559     }
560     appRecord->ApplicationTerminated();
561     // Maybe can't get in here
562     if (appRecord->IsKeepAliveApp()) {
563         return;
564     }
565     if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
566         HILOG_ERROR("current state is not background");
567         return;
568     }
569 
570     KillRenderProcess(appRecord);
571     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
572     appRecord->RemoveAppDeathRecipient();
573     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED);
574     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false);
575     appRunningManager_->RemoveAppRunningRecordById(recordId);
576     RemoveAppFromRecentListById(recordId);
577     AAFwk::EventInfo eventInfo;
578     auto applicationInfo = appRecord->GetApplicationInfo();
579     if (!applicationInfo) {
580         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
581     } else {
582         eventInfo.bundleName = applicationInfo->name;
583         eventInfo.versionName = applicationInfo->versionName;
584         eventInfo.versionCode = applicationInfo->versionCode;
585     }
586     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
587     eventInfo.processName = appRecord->GetProcessName();
588     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
589     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
590     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
591         RemoveRunningSharedBundleList(appRecord->GetBundleName());
592     }
593     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
594         OnAppStopped(appRecord);
595     }
596 
597     HILOG_INFO("application is terminated");
598     SendProcessExitEvent(appRecord->GetPriorityObject()->GetPid());
599 }
600 
UpdateApplicationInfoInstalled(const std::string & bundleName,const int uid)601 int32_t AppMgrServiceInner::UpdateApplicationInfoInstalled(const std::string &bundleName, const int uid)
602 {
603     if (!appRunningManager_) {
604         HILOG_ERROR("appRunningManager_ is nullptr");
605         return ERR_NO_INIT;
606     }
607 
608     int32_t result = VerifyRequestPermission();
609     if (result != ERR_OK) {
610         HILOG_ERROR("Permission verification failed");
611         return result;
612     }
613 
614     if (remoteClientManager_ == nullptr) {
615         HILOG_ERROR("remoteClientManager_ fail");
616         return ERR_NO_INIT;
617     }
618 
619     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
620     if (bundleMgr_ == nullptr) {
621         HILOG_ERROR("GetBundleManager fail");
622         return ERR_NO_INIT;
623     }
624     auto userId = GetUserIdByUid(uid);
625     ApplicationInfo appInfo;
626     HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetApplicationInfo");
627     bool bundleMgrResult = bundleMgr_->GetApplicationInfo(bundleName,
628         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo);
629     if (!bundleMgrResult) {
630         HILOG_ERROR("GetApplicationInfo is fail");
631         return ERR_INVALID_OPERATION;
632     }
633 
634     HILOG_DEBUG("uid value is %{public}d", uid);
635     result = appRunningManager_->ProcessUpdateApplicationInfoInstalled(appInfo);
636     if (result != ERR_OK) {
637         HILOG_INFO("The process corresponding to the package name did not start");
638     }
639 
640     return result;
641 }
642 
KillApplication(const std::string & bundleName)643 int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName)
644 {
645     if (!appRunningManager_) {
646         HILOG_ERROR("appRunningManager_ is nullptr");
647         return ERR_NO_INIT;
648     }
649 
650     auto result = VerifyProcessPermission(bundleName);
651     if (result != ERR_OK) {
652         HILOG_ERROR("Permission verification failed.");
653         return result;
654     }
655 
656     return KillApplicationByBundleName(bundleName);
657 }
658 
KillApplicationByUid(const std::string & bundleName,const int uid)659 int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid)
660 {
661     if (!appRunningManager_) {
662         HILOG_ERROR("appRunningManager_ is nullptr");
663         return ERR_NO_INIT;
664     }
665 
666     auto result = VerifyProcessPermission(bundleName);
667     if (result != ERR_OK) {
668         HILOG_ERROR("Permission verification failed.");
669         return result;
670     }
671 
672     result = ERR_OK;
673     int64_t startTime = SystemTimeMillisecond();
674     std::list<pid_t> pids;
675     if (remoteClientManager_ == nullptr) {
676         HILOG_ERROR("remoteClientManager_ fail");
677         return ERR_NO_INIT;
678     }
679     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
680     if (bundleMgr_ == nullptr) {
681         HILOG_ERROR("GetBundleManager fail");
682         return ERR_NO_INIT;
683     }
684     HILOG_INFO("uid value is %{public}d", uid);
685     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
686         HILOG_INFO("not start");
687         return result;
688     }
689     if (WaitForRemoteProcessExit(pids, startTime)) {
690         HILOG_INFO("The remote process exited successfully ");
691         return result;
692     }
693     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
694         result = KillProcessByPid(*iter);
695         if (result < 0) {
696             HILOG_ERROR("KillApplication failed for bundleName:%{public}s pid:%{public}d", bundleName.c_str(), *iter);
697             return result;
698         }
699     }
700     return result;
701 }
702 
SendProcessExitEventTask(pid_t pid,time_t exitTime,int32_t count)703 void AppMgrServiceInner::SendProcessExitEventTask(pid_t pid, time_t exitTime, int32_t count)
704 {
705     auto exitResult = !ProcessExist(pid);
706     constexpr int32_t EXIT_SUCESS = 0;
707     constexpr int32_t EXIT_FAILED = -1;
708 
709     if (exitResult) {
710         AAFwk::EventInfo eventInfo;
711         eventInfo.time = exitTime;
712         eventInfo.exitResult = EXIT_SUCESS;
713         eventInfo.pid = pid;
714         AAFwk::EventReport::SendAppEvent(AAFwk::EventName::PROCESS_EXIT, HiSysEventType::BEHAVIOR, eventInfo);
715         HILOG_INFO("time : %{public}" PRId64 ", exitResult : %{public}d, pid : %{public}d",
716             eventInfo.time, eventInfo.exitResult, eventInfo.pid);
717         return;
718     }
719 
720     if (--count <= 0) {
721         AAFwk::EventInfo eventInfo;
722         eventInfo.time = exitTime;
723         eventInfo.exitResult = EXIT_FAILED;
724         eventInfo.pid = pid;
725         AAFwk::EventReport::SendAppEvent(AAFwk::EventName::PROCESS_EXIT, HiSysEventType::BEHAVIOR, eventInfo);
726         HILOG_INFO("time : %{public}" PRId64 ", exitResult : %{public}d, pid : %{public}d",
727             eventInfo.time, eventInfo.exitResult, eventInfo.pid);
728         return;
729     }
730 
731     auto sendEventTask = [inner = shared_from_this(), pid, exitTime, count] () {
732         inner->SendProcessExitEventTask(pid, exitTime, count);
733     };
734     taskHandler_->SubmitTask(sendEventTask, PROCESS_EXIT_EVENT_TASK, KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
735 }
736 
SendProcessExitEvent(pid_t pid)737 void AppMgrServiceInner::SendProcessExitEvent(pid_t pid)
738 {
739     HILOG_INFO("%{public}s called.", __func__);
740     time_t currentTime;
741     time(&currentTime);
742     constexpr int32_t RETRY_COUNT = 5;
743     SendProcessExitEventTask(pid, currentTime, RETRY_COUNT);
744     return;
745 }
746 
KillApplicationSelf()747 int32_t AppMgrServiceInner::KillApplicationSelf()
748 {
749     if (!appRunningManager_) {
750         HILOG_ERROR("appRunningManager_ is nullptr");
751         return ERR_NO_INIT;
752     }
753 
754     auto callerPid = IPCSkeleton::GetCallingPid();
755     auto appRecord = GetAppRunningRecordByPid(callerPid);
756     if (!appRecord) {
757         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
758         return ERR_INVALID_VALUE;
759     }
760     auto bundleName = appRecord->GetBundleName();
761     return KillApplicationByBundleName(bundleName);
762 }
763 
KillApplicationByBundleName(const std::string & bundleName)764 int32_t AppMgrServiceInner::KillApplicationByBundleName(const std::string &bundleName)
765 {
766     int result = ERR_OK;
767     int64_t startTime = SystemTimeMillisecond();
768     std::list<pid_t> pids;
769 
770     if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids)) {
771         HILOG_ERROR("The process corresponding to the package name did not start");
772         return result;
773     }
774     if (WaitForRemoteProcessExit(pids, startTime)) {
775         HILOG_DEBUG("The remote process exited successfully ");
776         NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
777         return result;
778     }
779     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
780         result = KillProcessByPid(*iter);
781         if (result < 0) {
782             HILOG_ERROR("KillApplicationSelf is failed for bundleName:%{public}s, pid: %{public}d",
783                 bundleName.c_str(), *iter);
784             return result;
785         }
786     }
787     NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
788     return result;
789 }
790 
KillApplicationByUserId(const std::string & bundleName,const int userId)791 int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleName, const int userId)
792 {
793     if (!appRunningManager_) {
794         HILOG_ERROR("appRunningManager_ is nullptr");
795         return ERR_NO_INIT;
796     }
797     CHECK_CALLER_IS_SYSTEM_APP;
798     if (VerifyAccountPermission(
799         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES, userId) == ERR_PERMISSION_DENIED) {
800         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
801         return ERR_PERMISSION_DENIED;
802     }
803 
804     if (remoteClientManager_ == nullptr) {
805         HILOG_ERROR("remoteClientManager_ fail");
806         return ERR_NO_INIT;
807     }
808     auto bundleMgr = remoteClientManager_->GetBundleManager();
809     if (bundleMgr == nullptr) {
810         HILOG_ERROR("GetBundleManager fail");
811         return ERR_NO_INIT;
812     }
813 
814     return KillApplicationByUserIdLocked(bundleName, userId);
815 }
816 
KillApplicationByUserIdLocked(const std::string & bundleName,const int userId)817 int32_t AppMgrServiceInner::KillApplicationByUserIdLocked(const std::string &bundleName, const int userId)
818 {
819     if (!appRunningManager_) {
820         HILOG_ERROR("appRunningManager_ is nullptr");
821         return ERR_NO_INIT;
822     }
823 
824     int result = ERR_OK;
825     int64_t startTime = SystemTimeMillisecond();
826     std::list<pid_t> pids;
827     if (remoteClientManager_ == nullptr) {
828         HILOG_ERROR("remoteClientManager_ fail");
829         return ERR_NO_INIT;
830     }
831     auto bundleMgr = remoteClientManager_->GetBundleManager();
832     if (bundleMgr == nullptr) {
833         HILOG_ERROR("GetBundleManager fail");
834         return ERR_NO_INIT;
835     }
836 
837     HILOG_INFO("userId value is %{public}d", userId);
838     int uid = IN_PROCESS_CALL(bundleMgr->GetUidByBundleName(bundleName, userId));
839     HILOG_INFO("uid value is %{public}d", uid);
840     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
841         HILOG_INFO("The process corresponding to the package name did not start");
842         return result;
843     }
844     if (WaitForRemoteProcessExit(pids, startTime)) {
845         HILOG_INFO("The remote process exited successfully ");
846         return result;
847     }
848     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
849         result = KillProcessByPid(*iter);
850         if (result < 0) {
851             HILOG_ERROR("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter);
852             return result;
853         }
854     }
855     return result;
856 }
857 
ClearUpApplicationData(const std::string & bundleName,int32_t callerUid,pid_t callerPid)858 void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid)
859 {
860     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
861     auto userId = GetUserIdByUid(callerUid);
862     HILOG_INFO("userId:%{public}d", userId);
863     ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, userId);
864 }
865 
ClearUpApplicationDataByUserId(const std::string & bundleName,int32_t callerUid,pid_t callerPid,const int userId)866 void AppMgrServiceInner::ClearUpApplicationDataByUserId(
867     const std::string &bundleName, int32_t callerUid, pid_t callerPid, const int userId)
868 {
869     if (callerPid <= 0) {
870         HILOG_ERROR("invalid callerPid:%{public}d", callerPid);
871         return;
872     }
873     if (callerUid <= 0) {
874         HILOG_ERROR("invalid callerUid:%{public}d", callerUid);
875         return;
876     }
877     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
878     if (bundleMgr_ == nullptr) {
879         HILOG_ERROR("GetBundleManager fail");
880         return;
881     }
882 
883     // request to clear user information permission.
884     auto tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, 0);
885     int32_t result = AccessToken::AccessTokenKit::ClearUserGrantedPermissionState(tokenId);
886     if (result) {
887         HILOG_ERROR("ClearUserGrantedPermissionState failed, ret:%{public}d", result);
888         return;
889     }
890     // 2.delete bundle side user data
891     if (!IN_PROCESS_CALL(bundleMgr_->CleanBundleDataFiles(bundleName, userId))) {
892         HILOG_ERROR("Delete bundle side user data is fail");
893         return;
894     }
895     // 3.kill application
896     // 4.revoke user rights
897     result = KillApplicationByUserId(bundleName, userId);
898     if (result < 0) {
899         HILOG_ERROR("Kill Application by bundle name is fail");
900         return;
901     }
902     // 5.revoke uri permission rights
903     result = IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().RevokeAllUriPermissions(tokenId));
904     if (result != ERR_OK) {
905         HILOG_ERROR("Revoke all uri permissions is fail");
906         return;
907     }
908     NotifyAppStatusByCallerUid(bundleName, userId, callerUid,
909         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
910 }
911 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)912 int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
913 {
914     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
915     // check permission
916     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
917         const auto &appRecord = item.second;
918         if (!appRecord->GetSpawned()) {
919             continue;
920         }
921         if (isPerm) {
922             GetRunningProcesses(appRecord, info);
923         } else {
924             auto applicationInfo = appRecord->GetApplicationInfo();
925             if (!applicationInfo) {
926                 continue;
927             }
928             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
929             auto tokenId = applicationInfo->accessTokenId;
930             if (callingTokenId == tokenId) {
931                 GetRunningProcesses(appRecord, info);
932             }
933         }
934     }
935     return ERR_OK;
936 }
937 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)938 int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
939 {
940     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
941         ERR_PERMISSION_DENIED) {
942         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
943         return ERR_PERMISSION_DENIED;
944     }
945 
946     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
947         const auto &appRecord = item.second;
948         if (!appRecord->GetSpawned()) {
949             continue;
950         }
951         int32_t userIdTemp = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
952         if (userIdTemp == userId) {
953             GetRunningProcesses(appRecord, info);
954         }
955     }
956     return ERR_OK;
957 }
958 
GetProcessRunningInformation(RunningProcessInfo & info)959 int32_t AppMgrServiceInner::GetProcessRunningInformation(RunningProcessInfo &info)
960 {
961     if (!appRunningManager_) {
962         HILOG_ERROR("appRunningManager_ is nullptr");
963         return ERR_NO_INIT;
964     }
965     auto callerPid = IPCSkeleton::GetCallingPid();
966     auto appRecord = GetAppRunningRecordByPid(callerPid);
967     if (!appRecord) {
968         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
969         return ERR_INVALID_VALUE;
970     }
971     GetRunningProcess(appRecord, info);
972     return ERR_OK;
973 }
974 
GetAllRenderProcesses(std::vector<RenderProcessInfo> & info)975 int32_t AppMgrServiceInner::GetAllRenderProcesses(std::vector<RenderProcessInfo> &info)
976 {
977     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
978     // check permission
979     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
980         const auto &appRecord = item.second;
981         if (isPerm) {
982             GetRenderProcesses(appRecord, info);
983         } else {
984             auto applicationInfo = appRecord->GetApplicationInfo();
985             if (!applicationInfo) {
986                 continue;
987             }
988             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
989             auto tokenId = applicationInfo->accessTokenId;
990             if (callingTokenId == tokenId) {
991                 GetRenderProcesses(appRecord, info);
992             }
993         }
994     }
995     return ERR_OK;
996 }
997 
NotifyMemoryLevel(int32_t level)998 int32_t AppMgrServiceInner::NotifyMemoryLevel(int32_t level)
999 {
1000     HILOG_INFO("AppMgrServiceInner start");
1001 
1002     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
1003     auto isGatewayCall = AAFwk::PermissionVerification::GetInstance()->IsGatewayCall();
1004     if (!isSaCall && !isGatewayCall) {
1005         HILOG_ERROR("callerToken not SA %{public}s", __func__);
1006         return ERR_INVALID_VALUE;
1007     }
1008     if (!(level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_MODERATE ||
1009         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_CRITICAL ||
1010         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_LOW)) {
1011         HILOG_ERROR("Level value error!");
1012         return ERR_INVALID_VALUE;
1013     }
1014     if (!appRunningManager_) {
1015         HILOG_ERROR("appRunningManager nullptr!");
1016         return ERR_INVALID_VALUE;
1017     }
1018 
1019     return appRunningManager_->NotifyMemoryLevel(level);
1020 }
1021 
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)1022 int32_t AppMgrServiceInner::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
1023 {
1024     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
1025     if (!isSaCall) {
1026         HILOG_ERROR("callerToken not SA %{public}s", __func__);
1027         return ERR_INVALID_VALUE;
1028     }
1029     if (pid < 0) {
1030         HILOG_ERROR("pid is illegal!");
1031         return ERR_INVALID_VALUE;
1032     }
1033     if (!appRunningManager_) {
1034         HILOG_ERROR("appRunningManager nullptr!");
1035         return ERR_INVALID_VALUE;
1036     }
1037     return appRunningManager_->DumpHeapMemory(pid, mallocInfo);
1038 }
1039 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)1040 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
1041     std::vector<RunningProcessInfo> &info)
1042 {
1043     RunningProcessInfo runningProcessInfo;
1044     GetRunningProcess(appRecord, runningProcessInfo);
1045     info.emplace_back(runningProcessInfo);
1046 }
1047 
GetRunningProcess(const std::shared_ptr<AppRunningRecord> & appRecord,RunningProcessInfo & info)1048 void AppMgrServiceInner::GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
1049     RunningProcessInfo &info)
1050 {
1051     info.processName_ = appRecord->GetProcessName();
1052     info.pid_ = appRecord->GetPriorityObject()->GetPid();
1053     info.uid_ = appRecord->GetUid();
1054     info.state_ = static_cast<AppProcessState>(appRecord->GetState());
1055     info.isContinuousTask = appRecord->IsContinuousTask();
1056     info.isKeepAlive = appRecord->IsKeepAliveApp();
1057     info.isFocused = appRecord->GetFocusFlag();
1058     info.startTimeMillis_ = appRecord->GetAppStartTime();
1059     appRecord->GetBundleNames(info.bundleNames);
1060     info.processType_ = appRecord->GetProcessType();
1061     info.extensionType_ = AAFwk::UIExtensionUtils::ConvertType(appRecord->GetExtensionType());
1062 }
1063 
GetRenderProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RenderProcessInfo> & info)1064 void AppMgrServiceInner::GetRenderProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
1065     std::vector<RenderProcessInfo> &info)
1066 {
1067     auto renderRecordMap = appRecord->GetRenderRecordMap();
1068     if (renderRecordMap.empty()) {
1069         return;
1070     }
1071     for (auto iter : renderRecordMap) {
1072         auto renderRecord = iter.second;
1073         if (renderRecord != nullptr) {
1074             RenderProcessInfo renderProcessInfo;
1075             renderProcessInfo.bundleName_ = renderRecord->GetHostBundleName();
1076             renderProcessInfo.processName_ = renderRecord->GetProcessName();
1077             renderProcessInfo.pid_ = renderRecord->GetPid();
1078             renderProcessInfo.uid_ = renderRecord->GetUid();
1079             renderProcessInfo.hostUid_ = renderRecord->GetHostUid();
1080             info.emplace_back(renderProcessInfo);
1081         }
1082     }
1083 }
1084 
KillProcessByPid(const pid_t pid) const1085 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid) const
1086 {
1087     int32_t ret = -1;
1088     if (pid > 0) {
1089         HILOG_INFO("kill pid %{public}d", pid);
1090         ret = kill(pid, SIGNAL_KILL);
1091     }
1092     AAFwk::EventInfo eventInfo;
1093     auto appRecord = GetAppRunningRecordByPid(pid);
1094     if (!appRecord) {
1095         return ret;
1096     }
1097     auto applicationInfo = appRecord->GetApplicationInfo();
1098     if (!applicationInfo) {
1099         HILOG_ERROR("applicationInfo is nullptr, can not get app informations");
1100     } else {
1101         eventInfo.bundleName = applicationInfo->name;
1102         eventInfo.versionName = applicationInfo->versionName;
1103         eventInfo.versionCode = applicationInfo->versionCode;
1104     }
1105     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
1106     eventInfo.processName = appRecord->GetProcessName();
1107     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
1108     return ret;
1109 }
1110 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)1111 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
1112 {
1113     int64_t delayTime = SystemTimeMillisecond() - startTime;
1114     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
1115         if (CheckAllProcessExist(pids)) {
1116             return true;
1117         }
1118         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
1119         delayTime = SystemTimeMillisecond() - startTime;
1120     }
1121     return false;
1122 }
1123 
GetAllPids(std::list<pid_t> & pids)1124 bool AppMgrServiceInner::GetAllPids(std::list<pid_t> &pids)
1125 {
1126     for (const auto &appTaskInfo : appProcessManager_->GetRecentAppList()) {
1127         if (appTaskInfo) {
1128             auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
1129             if (appRecord) {
1130                 pids.push_back(appTaskInfo->GetPid());
1131                 appRecord->ScheduleProcessSecurityExit();
1132             }
1133         }
1134     }
1135     return (pids.empty() ? false : true);
1136 }
1137 
ProcessExist(pid_t & pid)1138 bool AppMgrServiceInner::ProcessExist(pid_t &pid)
1139 {
1140     char pid_path[128] = {0};
1141     struct stat stat_buf;
1142     if (!pid) {
1143         return false;
1144     }
1145     if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) {
1146         return false;
1147     }
1148     if (stat(pid_path, &stat_buf) == 0) {
1149         return true;
1150     }
1151     return false;
1152 }
1153 
CheckAllProcessExist(std::list<pid_t> & pids)1154 bool AppMgrServiceInner::CheckAllProcessExist(std::list<pid_t> &pids)
1155 {
1156     for (auto iter = pids.begin(); iter != pids.end();) {
1157         if (!ProcessExist(*iter)) {
1158             iter = pids.erase(iter);
1159         } else {
1160             iter++;
1161         }
1162     }
1163     if (pids.empty()) {
1164         return true;
1165     }
1166     return false;
1167 }
1168 
SystemTimeMillisecond()1169 int64_t AppMgrServiceInner::SystemTimeMillisecond()
1170 {
1171     struct timespec t;
1172     t.tv_sec = 0;
1173     t.tv_nsec = 0;
1174     clock_gettime(CLOCK_MONOTONIC, &t);
1175     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
1176 }
1177 
GetAppRunningRecordByPid(const pid_t pid) const1178 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
1179 {
1180     if (!appRunningManager_) {
1181         HILOG_ERROR("appRunningManager nullptr!");
1182         return nullptr;
1183     }
1184     return appRunningManager_->GetAppRunningRecordByPid(pid);
1185 }
1186 
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)1187 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(const sptr<IRemoteObject> &token,
1188     const sptr<IRemoteObject> &preToken, const std::shared_ptr<ApplicationInfo> &appInfo,
1189     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
1190     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1191 {
1192     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1193     if (!appRunningManager_) {
1194         HILOG_ERROR("appRunningManager nullptr!");
1195         return nullptr;
1196     }
1197     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
1198     if (!appRecord) {
1199         HILOG_ERROR("get app record failed");
1200         return nullptr;
1201     }
1202 
1203     appRecord->SetProcessAndExtensionType(abilityInfo);
1204     bool isKeepAlive = bundleInfo.isKeepAlive && bundleInfo.singleton;
1205     appRecord->SetKeepAliveAppState(isKeepAlive, false);
1206     appRecord->SetTaskHandler(taskHandler_);
1207     appRecord->SetEventHandler(eventHandler_);
1208     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1209     if (want) {
1210         appRecord->SetDebugApp(want->GetBoolParam("debugApp", false));
1211         appRecord->SetNativeDebug(want->GetBoolParam("nativeDebug", false));
1212         if (want->GetBoolParam(COLD_START, false)) {
1213             appRecord->SetDebugApp(true);
1214         }
1215         appRecord->SetAppIndex(want->GetIntParam(DLP_PARAMS_INDEX, 0));
1216         appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
1217         appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0));
1218         appRecord->SetCallerPid(want->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
1219         appRecord->SetCallerUid(want->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
1220         appRecord->SetCallerTokenId(want->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
1221     }
1222 
1223     if (preToken) {
1224         auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1225         if (abilityRecord) {
1226             abilityRecord->SetPreToken(preToken);
1227         }
1228     }
1229 
1230     return appRecord;
1231 }
1232 
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag)1233 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag)
1234 {
1235     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1236     HILOG_DEBUG("Terminate ability come.");
1237     if (!token) {
1238         HILOG_ERROR("AppMgrServiceInner::TerminateAbility token is null!");
1239         return;
1240     }
1241     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1242     if (!appRecord) {
1243         HILOG_ERROR("AppMgrServiceInner::TerminateAbility app is not exist!");
1244         return;
1245     }
1246 
1247     if (appRunningManager_) {
1248         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner = shared_from_this();
1249         appRunningManager_->TerminateAbility(token, clearMissionFlag, appMgrServiceInner);
1250     }
1251 }
1252 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)1253 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
1254 {
1255     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1256     HILOG_INFO("AppMgrService start to update the ability to state %{public}d.", static_cast<int32_t>(state));
1257     if (!token) {
1258         HILOG_ERROR("token is null!");
1259         return;
1260     }
1261 
1262     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1263     if (!appRecord) {
1264         HILOG_ERROR("app is not exist!");
1265         return;
1266     }
1267     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1268     if (!abilityRecord) {
1269         HILOG_ERROR("can not find ability record!");
1270         return;
1271     }
1272     if (state == abilityRecord->GetState()) {
1273         HILOG_ERROR("current state is already, no need update!");
1274         return;
1275     }
1276     if (abilityRecord->GetAbilityInfo() == nullptr) {
1277         HILOG_ERROR("ability info nullptr!");
1278         return;
1279     }
1280     auto type = abilityRecord->GetAbilityInfo()->type;
1281     if (type == AppExecFwk::AbilityType::SERVICE &&
1282         (state == AbilityState::ABILITY_STATE_CREATE ||
1283         state == AbilityState::ABILITY_STATE_TERMINATED ||
1284         state == AbilityState::ABILITY_STATE_CONNECTED ||
1285         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
1286         HILOG_INFO("StateChangedNotifyObserver service type, state:%{public}d", static_cast<int32_t>(state));
1287         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true);
1288         return;
1289     }
1290     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
1291         HILOG_ERROR("state is not foreground or background!");
1292         return;
1293     }
1294 
1295     appRecord->SetUpdateStateFromService(true);
1296     appRecord->UpdateAbilityState(token, state);
1297 }
1298 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)1299 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
1300 {
1301     if (!token) {
1302         HILOG_ERROR("token is null!");
1303         return;
1304     }
1305     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1306     if (!appRecord) {
1307         HILOG_ERROR("app is not exist!");
1308         return;
1309     }
1310     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1311     if (!abilityRecord) {
1312         HILOG_ERROR("can not find ability record!");
1313         return;
1314     }
1315     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false);
1316 }
1317 
OnStop()1318 void AppMgrServiceInner::OnStop()
1319 {
1320     if (!appRunningManager_) {
1321         HILOG_ERROR("appRunningManager nullptr!");
1322         return;
1323     }
1324 
1325     appRunningManager_->ClearAppRunningRecordMap();
1326     CloseAppSpawnConnection();
1327 }
1328 
OpenAppSpawnConnection()1329 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
1330 {
1331     if (remoteClientManager_ == nullptr) {
1332         HILOG_ERROR("remoteClientManager_ is null");
1333         return ERR_INVALID_VALUE;
1334     }
1335 
1336     if (remoteClientManager_->GetSpawnClient()) {
1337         return remoteClientManager_->GetSpawnClient()->OpenConnection();
1338     }
1339     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
1340 }
1341 
CloseAppSpawnConnection() const1342 void AppMgrServiceInner::CloseAppSpawnConnection() const
1343 {
1344     if (remoteClientManager_ == nullptr) {
1345         HILOG_ERROR("remoteClientManager_ is null");
1346         return;
1347     }
1348 
1349     if (remoteClientManager_->GetSpawnClient()) {
1350         remoteClientManager_->GetSpawnClient()->CloseConnection();
1351     }
1352 }
1353 
QueryAppSpawnConnectionState() const1354 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
1355 {
1356     if (remoteClientManager_ == nullptr) {
1357         HILOG_ERROR("remoteClientManager_ is null");
1358         return SpawnConnectionState::STATE_NOT_CONNECT;
1359     }
1360 
1361     if (remoteClientManager_->GetSpawnClient()) {
1362         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
1363     }
1364     return SpawnConnectionState::STATE_NOT_CONNECT;
1365 }
1366 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)1367 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
1368 {
1369     if (remoteClientManager_ == nullptr) {
1370         HILOG_ERROR("remoteClientManager_ is null");
1371         return;
1372     }
1373 
1374     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
1375 }
1376 
SetBundleManager(sptr<IBundleMgr> bundleManager)1377 void AppMgrServiceInner::SetBundleManager(sptr<IBundleMgr> bundleManager)
1378 {
1379     if (remoteClientManager_ == nullptr) {
1380         HILOG_ERROR("remoteClientManager_ is null");
1381         return;
1382     }
1383 
1384     remoteClientManager_->SetBundleManager(bundleManager);
1385 }
1386 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)1387 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
1388 {
1389     pid_t callingPid = IPCSkeleton::GetCallingPid();
1390     pid_t pid = getpid();
1391     if (callingPid != pid) {
1392         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
1393         return;
1394     }
1395     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1396     if (callback != nullptr) {
1397         std::lock_guard lock(appStateCallbacksLock_);
1398         appStateCallbacks_.push_back(callback);
1399     }
1400 }
1401 
AbilityBehaviorAnalysis(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const int32_t visibility,const int32_t perceptibility,const int32_t connectionState)1402 void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1403     const int32_t visibility,       // 0:false,1:true
1404     const int32_t perceptibility,   // 0:false,1:true
1405     const int32_t connectionState)  // 0:false,1:true
1406 {
1407     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1408     if (!token) {
1409         HILOG_ERROR("token is null");
1410         return;
1411     }
1412     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1413     if (!appRecord) {
1414         HILOG_ERROR("app record is not exist for ability token");
1415         return;
1416     }
1417     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1418     if (!abilityRecord) {
1419         HILOG_ERROR("ability record is not exist for ability previous token");
1420         return;
1421     }
1422     if (preToken) {
1423         abilityRecord->SetPreToken(preToken);
1424     }
1425     abilityRecord->SetVisibility(visibility);
1426     abilityRecord->SetPerceptibility(perceptibility);
1427     abilityRecord->SetConnectionState(connectionState);
1428 }
1429 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)1430 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
1431 {
1432     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1433     if (!token) {
1434         HILOG_ERROR("token is null");
1435         return;
1436     }
1437     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1438     if (!appRecord) {
1439         HILOG_ERROR("app record is not exist for ability token");
1440         return;
1441     }
1442 
1443     // before exec ScheduleProcessSecurityExit return
1444     // The resident process won't let him die
1445     if (appRecord->IsKeepAliveApp()) {
1446         return;
1447     }
1448 
1449     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1450     if (pid > 0) {
1451         std::list<pid_t> pids;
1452         pids.push_back(pid);
1453         appRecord->ScheduleProcessSecurityExit();
1454         if (!WaitForRemoteProcessExit(pids, SystemTimeMillisecond())) {
1455             int32_t result = KillProcessByPid(pid);
1456             if (result < 0) {
1457                 HILOG_ERROR("KillProcessByAbilityToken kill process is fail");
1458                 return;
1459             }
1460         }
1461     }
1462 }
1463 
KillProcessesByUserId(int32_t userId)1464 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId)
1465 {
1466     if (!appRunningManager_) {
1467         HILOG_ERROR("appRunningManager_ is nullptr");
1468         return;
1469     }
1470 
1471     int64_t startTime = SystemTimeMillisecond();
1472     std::list<pid_t> pids;
1473     if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
1474         HILOG_INFO("The process corresponding to the userId did not start");
1475         return;
1476     }
1477     if (WaitForRemoteProcessExit(pids, startTime)) {
1478         HILOG_INFO("The remote process exited successfully ");
1479         return;
1480     }
1481     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1482         auto result = KillProcessByPid(*iter);
1483         if (result < 0) {
1484             HILOG_ERROR("KillProcessByPid is failed. pid: %{public}d", *iter);
1485             return;
1486         }
1487     }
1488 }
1489 
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)1490 void AppMgrServiceInner::StartAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1491     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<AppRunningRecord> &appRecord,
1492     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1493 {
1494     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1495     HILOG_INFO("already create appRecord, just start ability");
1496     if (!appRecord) {
1497         HILOG_ERROR("appRecord is null");
1498         return;
1499     }
1500 
1501     if (want) {
1502         want->SetParam(DLP_PARAMS_SECURITY_FLAG, appRecord->GetSecurityFlag());
1503     }
1504 
1505     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
1506     if (abilityInfo->launchMode == LaunchMode::SINGLETON && ability != nullptr) {
1507         HILOG_WARN("same ability info in singleton launch mode, will not add ability");
1508         return;
1509     }
1510 
1511     if (ability && preToken) {
1512         HILOG_ERROR("Ability is already started");
1513         ability->SetPreToken(preToken);
1514         return;
1515     }
1516 
1517     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
1518     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1519     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
1520     if (!moduleRecord) {
1521         HILOG_ERROR("add moduleRecord failed");
1522         return;
1523     }
1524 
1525     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
1526     if (!ability) {
1527         HILOG_ERROR("add ability failed");
1528         return;
1529     }
1530 
1531     if (preToken != nullptr) {
1532         ability->SetPreToken(preToken);
1533     }
1534 
1535     ApplicationState appState = appRecord->GetState();
1536     if (appState == ApplicationState::APP_STATE_CREATE) {
1537         HILOG_ERROR("in create state, don't launch ability");
1538         return;
1539     }
1540     appRecord->LaunchAbility(ability);
1541 }
1542 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const1543 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
1544     const sptr<IRemoteObject> &abilityToken) const
1545 {
1546     if (!appRunningManager_) {
1547         HILOG_ERROR("appRunningManager_ is nullptr");
1548         return nullptr;
1549     }
1550 
1551     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
1552 }
1553 
GetTerminatingAppRunningRecord(const sptr<IRemoteObject> & token) const1554 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetTerminatingAppRunningRecord(
1555     const sptr<IRemoteObject> &token) const
1556 {
1557     if (!appRunningManager_) {
1558         HILOG_ERROR("appRunningManager_ is nullptr.");
1559         return nullptr;
1560     }
1561     return appRunningManager_->GetTerminatingAppRunningRecord(token);
1562 }
1563 
AbilityTerminated(const sptr<IRemoteObject> & token)1564 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
1565 {
1566     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1567     HILOG_DEBUG("Terminate ability come.");
1568     if (!token) {
1569         HILOG_ERROR("Terminate ability error, token is null!");
1570         return;
1571     }
1572 
1573     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
1574     if (!appRecord) {
1575         HILOG_ERROR("Terminate ability error, appRecord is not exist!");
1576         return;
1577     }
1578 
1579     appRecord->AbilityTerminated(token);
1580 }
1581 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const1582 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
1583 {
1584     if (appRunningManager_ == nullptr) {
1585         HILOG_ERROR("appRunningManager is nullptr");
1586         return nullptr;
1587     }
1588     const auto&& appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
1589     const auto& iter = appRunningRecordMap.find(recordId);
1590     return iter != appRunningRecordMap.end() ? iter->second : nullptr;
1591 }
1592 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp)1593 void AppMgrServiceInner::OnAppStateChanged(
1594     const std::shared_ptr<AppRunningRecord> &appRecord, const ApplicationState state, bool needNotifyApp)
1595 {
1596     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1597     if (!appRecord) {
1598         HILOG_ERROR("OnAppStateChanged come, app record is null");
1599         return;
1600     }
1601 
1602     HILOG_DEBUG("OnAppStateChanged begin, bundleName is %{public}s, state:%{public}d",
1603         appRecord->GetBundleName().c_str(), static_cast<int32_t>(state));
1604     {
1605         std::lock_guard lock(appStateCallbacksLock_);
1606         for (const auto &callback : appStateCallbacks_) {
1607             if (callback != nullptr) {
1608                 callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
1609             }
1610         }
1611     }
1612 
1613     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStateChanged(appRecord, state, needNotifyApp);
1614 }
1615 
OnAppStarted(const std::shared_ptr<AppRunningRecord> & appRecord)1616 void AppMgrServiceInner::OnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord)
1617 {
1618     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1619     if (!appRecord) {
1620         HILOG_ERROR("OnAppStarted come, app record is null");
1621         return;
1622     }
1623 
1624     if (appRecord->GetPriorityObject() == nullptr) {
1625         HILOG_ERROR("OnAppStarted come, appRecord's priorityobject is null");
1626         return;
1627     }
1628 
1629     HILOG_DEBUG("OnAppStarted begin, bundleName is %{public}s, pid:%{public}d",
1630         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
1631 
1632     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStarted(appRecord);
1633 }
1634 
1635 
OnAppStopped(const std::shared_ptr<AppRunningRecord> & appRecord)1636 void AppMgrServiceInner::OnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord)
1637 {
1638     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1639     if (!appRecord) {
1640         HILOG_ERROR("OnAppStopped come, app record is null");
1641         return;
1642     }
1643 
1644     if (appRecord->GetPriorityObject() == nullptr) {
1645         HILOG_ERROR("OnAppStarted come, appRecord's priorityObject is null");
1646         return;
1647     }
1648 
1649     HILOG_DEBUG("OnAppStopped begin, bundleName is %{public}s, pid:%{public}d",
1650         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
1651 
1652     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStopped(appRecord);
1653 }
1654 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1655 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
1656     const ApplicationState state)
1657 {
1658     AppProcessData processData;
1659     auto appInfoList = appRecord->GetAppInfoList();
1660     for (const auto &list : appInfoList) {
1661         AppData data;
1662         data.appName = list->name;
1663         data.uid = list->uid;
1664         processData.appDatas.push_back(data);
1665     }
1666     processData.processName = appRecord->GetProcessName();
1667     processData.pid = appRecord->GetPriorityObject()->GetPid();
1668     processData.appState = state;
1669     processData.isFocused = appRecord->GetFocusFlag();
1670     auto renderRecordMap = appRecord->GetRenderRecordMap();
1671     if (!renderRecordMap.empty()) {
1672         for (auto iter : renderRecordMap) {
1673             auto renderRecord = iter.second;
1674             if (renderRecord != nullptr) {
1675                 processData.renderPids.emplace_back(renderRecord->GetPid());
1676             }
1677         }
1678     }
1679     return processData;
1680 }
1681 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)1682 void AppMgrServiceInner::OnAbilityStateChanged(
1683     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
1684 {
1685     if (!ability) {
1686         HILOG_ERROR("ability is null");
1687         return;
1688     }
1689     std::lock_guard lock(appStateCallbacksLock_);
1690     for (const auto &callback : appStateCallbacks_) {
1691         if (callback != nullptr) {
1692             callback->OnAbilityRequestDone(ability->GetToken(), state);
1693         }
1694     }
1695 }
1696 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility)1697 void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility)
1698 {
1699     DelayedSingleton<AppStateObserverManager>::GetInstance()->StateChangedNotifyObserver(abilityStateData, isAbility);
1700 }
1701 
StartPerfProcess(const std::shared_ptr<AppRunningRecord> & appRecord,const std::string & perfCmd,const std::string & debugCmd,bool isSanboxApp) const1702 int32_t AppMgrServiceInner::StartPerfProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
1703     const std::string& perfCmd, const std::string& debugCmd, bool isSanboxApp) const
1704 {
1705     if (!remoteClientManager_->GetSpawnClient() || !appRecord) {
1706         HILOG_ERROR("appSpawnClient or appRecord is null");
1707         return ERR_INVALID_OPERATION;
1708     }
1709     if (perfCmd.empty() && debugCmd.empty()) {
1710         HILOG_DEBUG("perfCmd is empty");
1711         return ERR_INVALID_OPERATION;
1712     }
1713 
1714     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
1715     if (!perfCmd.empty()) {
1716         HILOG_DEBUG("debuggablePipe perfCmd:%{public}s", perfCmd.c_str());
1717     } else {
1718         HILOG_DEBUG("debuggablePipe debugCmd:%{public}s", debugCmd.c_str());
1719     }
1720     if (isSanboxApp) {
1721         HILOG_DEBUG("debuggablePipe sandbox: true");
1722     }
1723     return ERR_OK;
1724 }
1725 
SetOverlayInfo(const std::string & bundleName,const int32_t userId,AppSpawnStartMsg & startMsg)1726 void AppMgrServiceInner::SetOverlayInfo(const std::string &bundleName,
1727                                         const int32_t userId,
1728                                         AppSpawnStartMsg &startMsg)
1729 {
1730     if (remoteClientManager_ == nullptr) {
1731         HILOG_ERROR("remoteClientManager_ fail");
1732         return;
1733     }
1734     auto bundleMgr = remoteClientManager_->GetBundleManager();
1735     if (bundleMgr == nullptr) {
1736         HILOG_ERROR("GetBundleManager fail");
1737         return;
1738     }
1739     auto overlayMgrProxy = bundleMgr->GetOverlayManagerProxy();
1740     if (overlayMgrProxy !=  nullptr) {
1741         std::vector<OverlayModuleInfo> overlayModuleInfo;
1742         HILOG_DEBUG("Check overlay app begin.");
1743         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetOverlayModuleInfoForTarget");
1744         auto targetRet = IN_PROCESS_CALL(overlayMgrProxy->GetOverlayModuleInfoForTarget(
1745             bundleName, "", overlayModuleInfo, userId));
1746         if (targetRet == ERR_OK && overlayModuleInfo.size() != 0) {
1747             HILOG_DEBUG("Start an overlay app process.");
1748             startMsg.flags = startMsg.flags | APP_OVERLAY_FLAG;
1749             std::string overlayInfoPaths;
1750             for (auto it : overlayModuleInfo) {
1751                 overlayInfoPaths += (it.hapPath + "|");
1752             }
1753             startMsg.overlayInfo = overlayInfoPaths;
1754         }
1755     }
1756 }
1757 
StartProcessVerifyPermission(const BundleInfo & bundleInfo,bool & hasAccessBundleDirReq,uint8_t & setAllowInternet,uint8_t & allowInternet,std::vector<int32_t> & gids,std::set<std::string> & permissions)1758 void AppMgrServiceInner::StartProcessVerifyPermission(const BundleInfo &bundleInfo, bool &hasAccessBundleDirReq,
1759                                                       uint8_t &setAllowInternet, uint8_t &allowInternet,
1760                                                       std::vector<int32_t> &gids, std::set<std::string> &permissions)
1761 {
1762     hasAccessBundleDirReq = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
1763         [] (const auto &reqPermission) {
1764             if (PERMISSION_ACCESS_BUNDLE_DIR == reqPermission) {
1765                 return true;
1766             }
1767             return false;
1768         });
1769 
1770     auto token = bundleInfo.applicationInfo.accessTokenId;
1771     {
1772         HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::VerifyAccessToken");
1773         int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_INTERNET);
1774         if (result != Security::AccessToken::PERMISSION_GRANTED) {
1775             setAllowInternet = 1;
1776             allowInternet = 0;
1777     #ifdef APP_MGR_SERVICE_APPMS
1778             auto ret = SetInternetPermission(bundleInfo.uid, 0);
1779             HILOG_DEBUG("SetInternetPermission, ret = %{public}d", ret);
1780         } else {
1781             auto ret = SetInternetPermission(bundleInfo.uid, 1);
1782             HILOG_DEBUG("SetInternetPermission, ret = %{public}d", ret);
1783             gids.push_back(NETSYS_SOCKET_GROUPID);
1784     #endif
1785         }
1786 
1787         result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_MANAGE_VPN);
1788         if (result == Security::AccessToken::PERMISSION_GRANTED) {
1789             gids.push_back(BLUETOOTH_GROUPID);
1790         }
1791 
1792         if (hasAccessBundleDirReq) {
1793             int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_ACCESS_BUNDLE_DIR);
1794             if (result != Security::AccessToken::PERMISSION_GRANTED) {
1795                 HILOG_ERROR("StartProcess PERMISSION_ACCESS_BUNDLE_DIR NOT GRANTED");
1796                 hasAccessBundleDirReq = false;
1797             }
1798         }
1799     }
1800 
1801     std::set<std::string> mountPermissionList = AppSpawn::AppspawnMountPermission::GetMountPermissionList();
1802     for (std::string permission : mountPermissionList) {
1803         if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, permission) ==
1804             Security::AccessToken::PERMISSION_GRANTED) {
1805             permissions.insert(permission);
1806         }
1807     }
1808 }
1809 
StartProcess(const std::string & appName,const std::string & processName,uint32_t startFlags,const std::shared_ptr<AppRunningRecord> & appRecord,const int uid,const std::string & bundleName,const int32_t bundleIndex,bool appExistFlag)1810 void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags,
1811                                       const std::shared_ptr<AppRunningRecord> &appRecord, const int uid,
1812                                       const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag)
1813 {
1814     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1815     if (!appRecord) {
1816         HILOG_ERROR("appRecord is null");
1817         return;
1818     }
1819 
1820     if (!remoteClientManager_->GetSpawnClient()) {
1821         HILOG_ERROR("appSpawnClient is null");
1822         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1823         return;
1824     }
1825 
1826     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
1827     if (bundleMgr_ == nullptr) {
1828         HILOG_ERROR("GetBundleManager fail");
1829         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1830         return;
1831     }
1832 
1833     auto userId = GetUserIdByUid(uid);
1834     BundleInfo bundleInfo;
1835     bool bundleMgrResult;
1836     if (bundleIndex == 0) {
1837         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetBundleInfo");
1838         bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfo(bundleName,
1839             BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION, bundleInfo, userId));
1840     } else {
1841         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetSandboxBundleInfo");
1842         bundleMgrResult = (IN_PROCESS_CALL(bundleMgr_->GetSandboxBundleInfo(bundleName,
1843             bundleIndex, userId, bundleInfo)) == 0);
1844     }
1845 
1846     if (!bundleMgrResult) {
1847         HILOG_ERROR("GetBundleInfo is fail");
1848         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1849         return;
1850     }
1851 
1852     HspList hspList;
1853     ErrCode ret = bundleMgr_->GetBaseSharedBundleInfos(bundleName, hspList);
1854     if (ret != ERR_OK) {
1855         HILOG_ERROR("GetBaseSharedBundleInfos failed: %d", ret);
1856         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1857         return;
1858     }
1859 
1860     DataGroupInfoList dataGroupInfoList;
1861     bool result = bundleMgr_->QueryDataGroupInfos(bundleName, userId, dataGroupInfoList);
1862     if (!result || dataGroupInfoList.empty()) {
1863         HILOG_DEBUG("the bundle has no groupInfos");
1864     }
1865 
1866     bool hasAccessBundleDirReq;
1867     uint8_t setAllowInternet = 0;
1868     uint8_t allowInternet = 1;
1869     std::vector<int32_t> gids;
1870     std::set<std::string> permissions;
1871     StartProcessVerifyPermission(bundleInfo, hasAccessBundleDirReq, setAllowInternet, allowInternet, gids,
1872                                  permissions);
1873 
1874     AppSpawnStartMsg startMsg;
1875     startMsg.uid = bundleInfo.uid;
1876     startMsg.gid = bundleInfo.gid;
1877     startMsg.gids = gids;
1878     startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId;
1879     startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel;
1880     startMsg.bundleName = bundleName;
1881     startMsg.renderParam = RENDER_PARAM;
1882     startMsg.flags = startFlags;
1883     startMsg.bundleIndex = bundleIndex;
1884     startMsg.setAllowInternet = setAllowInternet;
1885     startMsg.allowInternet = allowInternet;
1886     startMsg.hspList = hspList;
1887     startMsg.dataGroupInfoList = dataGroupInfoList;
1888     startMsg.hapFlags = bundleInfo.isPreInstallApp ? 1 : 0;
1889 
1890     startMsg.mountPermissionFlags = AppSpawn::AppspawnMountPermission::GenPermissionCode(permissions);
1891     if (hasAccessBundleDirReq) {
1892         startMsg.flags = startMsg.flags | APP_ACCESS_BUNDLE_DIR;
1893     }
1894 
1895     SetOverlayInfo(bundleName, userId, startMsg);
1896 
1897     HILOG_DEBUG("Start process, apl is %{public}s, bundleName is %{public}s, startFlags is %{public}d.",
1898         startMsg.apl.c_str(), bundleName.c_str(), startFlags);
1899 
1900     bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleGidsByUid(bundleName, uid, startMsg.gids));
1901     if (!bundleMgrResult) {
1902         HILOG_ERROR("GetBundleGids is fail");
1903         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1904         return;
1905     }
1906 
1907     startMsg.procName = processName;
1908     startMsg.accessTokenIdEx = bundleInfo.applicationInfo.accessTokenIdEx;
1909 
1910     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
1911     pid_t pid = 0;
1912     ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
1913     if (FAILED(errCode)) {
1914         HILOG_ERROR("failed to spawn new app process, errCode %{public}08x", errCode);
1915         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1916         return;
1917     }
1918     HILOG_INFO("Start process success, pid is %{public}d, processName is %{public}s.", pid, processName.c_str());
1919     SetRunningSharedBundleList(bundleName, hspList);
1920     appRecord->GetPriorityObject()->SetPid(pid);
1921     appRecord->SetUid(startMsg.uid);
1922     appRecord->SetStartMsg(startMsg);
1923     appRecord->SetAppMgrServiceInner(weak_from_this());
1924     appRecord->SetSpawned();
1925     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false);
1926     AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
1927     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessCreated(appRecord);
1928     if (!appExistFlag) {
1929         OnAppStarted(appRecord);
1930     }
1931     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
1932     SendProcessStartEvent(appRecord);
1933 }
1934 
UpDateStartupType(const std::shared_ptr<AbilityInfo> & info,int32_t & abilityType,int32_t & extensionType)1935 void AppMgrServiceInner::UpDateStartupType(
1936     const std::shared_ptr<AbilityInfo> &info, int32_t &abilityType, int32_t &extensionType)
1937 {
1938     if (info == nullptr) {
1939         return;
1940     }
1941 
1942     HILOG_DEBUG("bundleName:%{public}s, abilityName:%{public}s", info->bundleName.c_str(), info->name.c_str());
1943     abilityType = static_cast<int32_t>(info->type);
1944     if (info->type != AbilityType::EXTENSION) {
1945         return;
1946     }
1947 
1948     extensionType = static_cast<int32_t>(info->extensionAbilityType);
1949 }
1950 
SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> & appRecord)1951 bool AppMgrServiceInner::SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
1952 {
1953     if (!appRecord) {
1954         HILOG_ERROR("appRecord is nullptr");
1955         return false;
1956     }
1957 
1958     AAFwk::EventInfo eventInfo;
1959     time_t currentTime;
1960     time(&currentTime);
1961     eventInfo.time = currentTime;
1962     eventInfo.callerUid = appRecord->GetCallerUid() == -1 ? IPCSkeleton::GetCallingUid() : appRecord->GetCallerUid();
1963     if (!appRecord->GetAbilities().empty()) {
1964         auto abilityinfo = appRecord->GetAbilities().begin()->second->GetAbilityInfo();
1965         UpDateStartupType(abilityinfo, eventInfo.abilityType, eventInfo.extensionType);
1966     } else {
1967         HILOG_INFO("Abilities nullptr!");
1968     }
1969 
1970     auto callerAppRecord = GetAppRunningRecordByPid(appRecord->GetCallerPid());
1971     if (callerAppRecord == nullptr) {
1972         Security::AccessToken::NativeTokenInfo nativeTokenInfo = {};
1973         auto token = appRecord->GetCallerTokenId() == -1 ?
1974             static_cast<int>(IPCSkeleton::GetCallingTokenID()) : appRecord->GetCallerTokenId();
1975         Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(token, nativeTokenInfo);
1976         eventInfo.callerBundleName = "";
1977         eventInfo.callerProcessName = nativeTokenInfo.processName;
1978     } else {
1979         if (callerAppRecord->GetBundleName().empty()) {
1980             eventInfo.callerBundleName = callerAppRecord->GetName();
1981         } else {
1982             eventInfo.callerBundleName = callerAppRecord->GetBundleName();
1983         }
1984         eventInfo.callerProcessName = callerAppRecord->GetProcessName();
1985     }
1986     if (!appRecord->GetBundleName().empty()) {
1987         eventInfo.bundleName = appRecord->GetBundleName();
1988     }
1989     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::PROCESS_START, HiSysEventType::BEHAVIOR, eventInfo);
1990     HILOG_DEBUG("%{public}s. time : %{public}" PRId64 ", abilityType : %{public}d, bundle : %{public}s,\
1991         uid : %{public}d, process : %{public}s",
1992         __func__, eventInfo.time, eventInfo.abilityType, eventInfo.callerBundleName.c_str(), eventInfo.callerUid,
1993         eventInfo.callerProcessName.c_str());
1994 
1995     return true;
1996 }
1997 
SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AbilityInfo> & abilityInfo,const AppStartType startType)1998 void AppMgrServiceInner::SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
1999     const std::shared_ptr<AbilityInfo> &abilityInfo, const AppStartType startType)
2000 {
2001     if (!appRecord) {
2002         HILOG_ERROR("appRecord is nullptr");
2003         return;
2004     }
2005     AAFwk::EventInfo eventInfo;
2006     auto applicationInfo = appRecord->GetApplicationInfo();
2007     if (!applicationInfo) {
2008         HILOG_ERROR("applicationInfo is nullptr, can not get app information");
2009     } else {
2010         eventInfo.bundleName = applicationInfo->name;
2011         eventInfo.versionName = applicationInfo->versionName;
2012         eventInfo.versionCode = applicationInfo->versionCode;
2013     }
2014     if (!abilityInfo) {
2015         HILOG_ERROR("abilityInfo is nullptr, can not get ability information");
2016     } else {
2017         eventInfo.abilityName = abilityInfo->name;
2018     }
2019     if (appRecord->GetPriorityObject() == nullptr) {
2020         HILOG_ERROR("appRecord's priorityObject is null");
2021     } else {
2022         eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
2023     }
2024     eventInfo.startType = static_cast<int32_t>(startType);
2025     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
2026 }
2027 
RemoveAppFromRecentList(const std::string & appName,const std::string & processName)2028 void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, const std::string &processName)
2029 {
2030     int64_t startTime = 0;
2031     std::list<pid_t> pids;
2032     auto appTaskInfo = appProcessManager_->GetAppTaskInfoByProcessName(appName, processName);
2033     if (!appTaskInfo) {
2034         return;
2035     }
2036     auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
2037     if (!appRecord) {
2038         appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
2039         return;
2040     }
2041 
2042     // Do not delete resident processes, before exec ScheduleProcessSecurityExit
2043     if (appRecord->IsKeepAliveApp()) {
2044         return;
2045     }
2046 
2047     startTime = SystemTimeMillisecond();
2048     pids.push_back(appTaskInfo->GetPid());
2049     appRecord->ScheduleProcessSecurityExit();
2050     if (!WaitForRemoteProcessExit(pids, startTime)) {
2051         int32_t result = KillProcessByPid(appTaskInfo->GetPid());
2052         if (result < 0) {
2053             HILOG_ERROR("RemoveAppFromRecentList kill process is fail");
2054             return;
2055         }
2056     }
2057     appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
2058 }
2059 
GetRecentAppList() const2060 const std::list<const std::shared_ptr<AppTaskInfo>> &AppMgrServiceInner::GetRecentAppList() const
2061 {
2062     return appProcessManager_->GetRecentAppList();
2063 }
2064 
ClearRecentAppList()2065 void AppMgrServiceInner::ClearRecentAppList()
2066 {
2067     int64_t startTime = 0;
2068     std::list<pid_t> pids;
2069     if (GetAllPids(pids)) {
2070         return;
2071     }
2072 
2073     startTime = SystemTimeMillisecond();
2074     if (WaitForRemoteProcessExit(pids, startTime)) {
2075         appProcessManager_->ClearRecentAppList();
2076         return;
2077     }
2078     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
2079         int32_t result = KillProcessByPid(*iter);
2080         if (result < 0) {
2081             HILOG_ERROR("ClearRecentAppList kill process is fail");
2082             return;
2083         }
2084     }
2085     appProcessManager_->ClearRecentAppList();
2086 }
2087 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess)2088 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess)
2089 {
2090     HILOG_ERROR("On remote died.");
2091     if (isRenderProcess) {
2092         OnRenderRemoteDied(remote);
2093         return;
2094     }
2095 
2096     auto appRecord = appRunningManager_->OnRemoteDied(remote);
2097     if (!appRecord) {
2098         return;
2099     }
2100 
2101     ClearAppRunningData(appRecord, false);
2102     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
2103         RemoveRunningSharedBundleList(appRecord->GetBundleName());
2104     }
2105 }
2106 
ClearAppRunningData(const std::shared_ptr<AppRunningRecord> & appRecord,bool containsApp)2107 void AppMgrServiceInner::ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord, bool containsApp)
2108 {
2109     if (!appRecord) {
2110         return;
2111     }
2112 
2113     if (containsApp) {
2114         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2115     }
2116 
2117     FinishUserTestLocked("App died", -1, appRecord);
2118     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_REMOTE_DIED);
2119 
2120     for (const auto &item : appRecord->GetAbilities()) {
2121         const auto &abilityRecord = item.second;
2122         appRecord->StateChangedNotifyObserver(abilityRecord,
2123             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true);
2124     }
2125     RemoveAppFromRecentListById(appRecord->GetRecordId());
2126     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
2127 
2128     // kill render if exist.
2129     KillRenderProcess(appRecord);
2130 
2131     if (appRecord->GetPriorityObject() != nullptr) {
2132         SendProcessExitEvent(appRecord->GetPriorityObject()->GetPid());
2133     }
2134 
2135     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
2136         OnAppStopped(appRecord);
2137     }
2138 
2139     if (appRecord->IsKeepAliveApp()) {
2140         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
2141             innerService->RestartResidentProcess(appRecord);
2142         };
2143         if (!taskHandler_) {
2144             HILOG_ERROR("taskHandler_ is nullptr");
2145             return;
2146         }
2147         if (appRecord->CanRestartResidentProc()) {
2148             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcess");
2149         } else {
2150             auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
2151                 return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
2152             };
2153             auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(),
2154                 findRestartResidentTask);
2155             if (findIter != restartResedentTaskList_.end()) {
2156                 HILOG_WARN("The restart app task has been registered.");
2157                 return;
2158             }
2159             restartResedentTaskList_.emplace_back(appRecord);
2160             HILOG_INFO("PostRestartResidentProcessDelayTask.");
2161             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcessDelayTask", RESTART_INTERVAL_TIME);
2162         }
2163     }
2164 }
2165 
PushAppFront(const int32_t recordId)2166 void AppMgrServiceInner::PushAppFront(const int32_t recordId)
2167 {
2168     appProcessManager_->PushAppFront(recordId);
2169 }
2170 
RemoveAppFromRecentListById(const int32_t recordId)2171 void AppMgrServiceInner::RemoveAppFromRecentListById(const int32_t recordId)
2172 {
2173     appProcessManager_->RemoveAppFromRecentListById(recordId);
2174 }
2175 
AddAppToRecentList(const std::string & appName,const std::string & processName,const pid_t pid,const int32_t recordId)2176 void AppMgrServiceInner::AddAppToRecentList(
2177     const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId)
2178 {
2179     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2180     appProcessManager_->AddAppToRecentList(appName, processName, pid, recordId);
2181 }
2182 
GetAppTaskInfoById(const int32_t recordId) const2183 const std::shared_ptr<AppTaskInfo> AppMgrServiceInner::GetAppTaskInfoById(const int32_t recordId) const
2184 {
2185     return appProcessManager_->GetAppTaskInfoById(recordId);
2186 }
2187 
AddAppDeathRecipient(const pid_t pid,const sptr<AppDeathRecipient> & appDeathRecipient) const2188 void AppMgrServiceInner::AddAppDeathRecipient(const pid_t pid, const sptr<AppDeathRecipient> &appDeathRecipient) const
2189 {
2190     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2191     std::shared_ptr<AppRunningRecord> appRecord = GetAppRunningRecordByPid(pid);
2192     if (appRecord) {
2193         appRecord->SetAppDeathRecipient(appDeathRecipient);
2194     }
2195 }
2196 
HandleTimeOut(const AAFwk::EventWrap & event)2197 void AppMgrServiceInner::HandleTimeOut(const AAFwk::EventWrap &event)
2198 {
2199     HILOG_INFO("handle time out");
2200     if (!appRunningManager_) {
2201         HILOG_ERROR("appRunningManager is nullptr");
2202         return;
2203     }
2204 
2205     // check libc.hook_mode
2206     const int bufferLen = 128;
2207     char paramOutBuf[bufferLen] = {0};
2208     const char *hook_mode = "startup:";
2209     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
2210     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
2211         HILOG_DEBUG("HandleTimeOut, Hook_mode: no handle time out");
2212         return;
2213     }
2214 
2215     switch (event.GetEventId()) {
2216         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
2217             appRunningManager_->HandleTerminateTimeOut(event.GetParam());
2218             break;
2219         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
2220             SendHiSysEvent(event.GetEventId(), event.GetParam());
2221             HandleTerminateApplicationTimeOut(event.GetParam());
2222             break;
2223         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
2224         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
2225             SendHiSysEvent(event.GetEventId(), event.GetParam());
2226             HandleAddAbilityStageTimeOut(event.GetParam());
2227             break;
2228         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
2229             SendHiSysEvent(event.GetEventId(), event.GetParam());
2230             HandleStartSpecifiedAbilityTimeOut(event.GetParam());
2231             break;
2232         default:
2233             break;
2234     }
2235 }
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)2236 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
2237 {
2238     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2239     HILOG_INFO("%{public}s called", __func__);
2240     if (!appRunningManager_) {
2241         HILOG_ERROR("appRunningManager_ is nullptr");
2242         return;
2243     }
2244     appRunningManager_->HandleAbilityAttachTimeOut(token);
2245 }
2246 
PrepareTerminate(const sptr<IRemoteObject> & token)2247 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token)
2248 {
2249     HILOG_INFO("AppMgrService prepare to terminate the ability.");
2250     if (!appRunningManager_) {
2251         HILOG_ERROR("appRunningManager_ is nullptr");
2252         return;
2253     }
2254     appRunningManager_->PrepareTerminate(token);
2255 }
2256 
HandleTerminateApplicationTimeOut(const int64_t eventId)2257 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId)
2258 {
2259     HILOG_INFO("handle terminate application time out");
2260     if (!appRunningManager_) {
2261         HILOG_ERROR("appRunningManager_ is nullptr");
2262         return;
2263     }
2264     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2265     TerminateApplication(appRecord);
2266 }
2267 
TerminateApplication(const std::shared_ptr<AppRunningRecord> & appRecord)2268 void AppMgrServiceInner::TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
2269 {
2270     if (!appRecord) {
2271         HILOG_ERROR("appRecord is nullptr");
2272         return;
2273     }
2274     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
2275     appRecord->RemoveAppDeathRecipient();
2276     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT);
2277     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false);
2278     pid_t pid = appRecord->GetPriorityObject()->GetPid();
2279     if (pid > 0) {
2280         auto timeoutTask = [pid, innerService = shared_from_this()]() {
2281             HILOG_INFO("KillProcessByPid %{public}d", pid);
2282             int32_t result = innerService->KillProcessByPid(pid);
2283             innerService->SendProcessExitEvent(pid);
2284             if (result < 0) {
2285                 HILOG_ERROR("KillProcessByPid kill process is fail");
2286                 return;
2287             }
2288         };
2289         if (!taskHandler_) {
2290             HILOG_ERROR("taskHandler_ is nullptr");
2291             return;
2292         }
2293         taskHandler_->SubmitTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
2294     }
2295     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
2296     RemoveAppFromRecentListById(appRecord->GetRecordId());
2297     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
2298         RemoveRunningSharedBundleList(appRecord->GetBundleName());
2299     }
2300     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
2301     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
2302         OnAppStopped(appRecord);
2303     }
2304 }
2305 
HandleAddAbilityStageTimeOut(const int64_t eventId)2306 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId)
2307 {
2308     HILOG_INFO("called add ability stage info time out!");
2309     if (!appRunningManager_) {
2310         HILOG_ERROR("appRunningManager_ is nullptr");
2311         return;
2312     }
2313     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2314     if (!appRecord) {
2315         HILOG_ERROR("appRecord is nullptr");
2316         return;
2317     }
2318 
2319     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
2320         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
2321     }
2322 
2323     KillApplicationByRecord(appRecord);
2324 }
2325 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)2326 void AppMgrServiceInner::GetRunningProcessInfoByToken(
2327     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
2328 {
2329     HILOG_DEBUG("called");
2330     if (!CheckGetRunningInfoPermission()) {
2331         return;
2332     }
2333 
2334     appRunningManager_->GetRunningProcessInfoByToken(token, info);
2335 }
2336 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info) const2337 void AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const
2338 {
2339     HILOG_DEBUG("called");
2340     if (!CheckGetRunningInfoPermission()) {
2341         return;
2342     }
2343 
2344     appRunningManager_->GetRunningProcessInfoByPid(pid, info);
2345 }
2346 
SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const2347 void AppMgrServiceInner::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const
2348 {
2349     HILOG_DEBUG("called");
2350     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2351         return;
2352     }
2353 
2354     appRunningManager_->SetAbilityForegroundingFlagToAppRecord(pid);
2355 }
2356 
CheckGetRunningInfoPermission() const2357 bool AppMgrServiceInner::CheckGetRunningInfoPermission() const
2358 {
2359     if (!appRunningManager_) {
2360         HILOG_ERROR("appRunningManager_ is nullptr");
2361         return false;
2362     }
2363 
2364     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2365     if (!isPerm) {
2366         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2367         return false;
2368     }
2369 
2370     return true;
2371 }
2372 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)2373 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
2374 {
2375     HILOG_INFO("%{public}s called", __func__);
2376 
2377     HILOG_INFO("bundle info size: [%{public}zu]", infos.size());
2378     StartResidentProcess(infos, -1, true);
2379 }
2380 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount,bool isEmptyKeepAliveApp)2381 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount,
2382     bool isEmptyKeepAliveApp)
2383 {
2384     HILOG_INFO("start resident process");
2385     if (infos.empty()) {
2386         HILOG_ERROR("infos is empty!");
2387         return;
2388     }
2389 
2390     if (!appRunningManager_) {
2391         HILOG_ERROR("appRunningManager_ is nullptr");
2392         return;
2393     }
2394 
2395     for (auto &bundle : infos) {
2396         HILOG_INFO("processName = [%{public}s]", bundle.applicationInfo.process.c_str());
2397         if (bundle.applicationInfo.process.empty()) {
2398             continue;
2399         }
2400         auto processName = bundle.applicationInfo.process;
2401         // Inspection records
2402         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
2403             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
2404         if (appRecord) {
2405             HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
2406             continue;
2407         }
2408         HILOG_INFO("Start empty resident process, processName = [%{public}s]", processName.c_str());
2409         StartEmptyResidentProcess(bundle, processName, restartCount, isEmptyKeepAliveApp);
2410     }
2411 }
2412 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount,bool isEmptyKeepAliveApp)2413 void AppMgrServiceInner::StartEmptyResidentProcess(
2414     const BundleInfo &info, const std::string &processName, int restartCount, bool isEmptyKeepAliveApp)
2415 {
2416     HILOG_INFO("start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
2417     if (!CheckRemoteClient() || !appRunningManager_) {
2418         HILOG_INFO("Failed to start resident process!");
2419         return;
2420     }
2421 
2422     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name);
2423     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
2424     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
2425     if (!appRecord) {
2426         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2427         return;
2428     }
2429 
2430     StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, appInfo->bundleName, 0, appExistFlag);
2431 
2432     // If it is empty, the startup failed
2433     if (!appRecord) {
2434         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2435         return;
2436     }
2437 
2438     appRecord->SetKeepAliveAppState(true, isEmptyKeepAliveApp);
2439 
2440     if (restartCount > 0) {
2441         HILOG_INFO("StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount);
2442         appRecord->SetRestartResidentProcCount(restartCount);
2443     }
2444 
2445     appRecord->SetTaskHandler(taskHandler_);
2446     appRecord->SetEventHandler(eventHandler_);
2447     appRecord->AddModules(appInfo, info.hapModuleInfos);
2448     HILOG_INFO("StartEmptyResidentProcess of pid : [%{public}d], ", appRecord->GetPriorityObject()->GetPid());
2449 }
2450 
CheckRemoteClient()2451 bool AppMgrServiceInner::CheckRemoteClient()
2452 {
2453     if (!remoteClientManager_) {
2454         HILOG_ERROR("remoteClientManager_ is null");
2455         return false;
2456     }
2457 
2458     if (!remoteClientManager_->GetSpawnClient()) {
2459         HILOG_ERROR("appSpawnClient is null");
2460         return false;
2461     }
2462 
2463     if (!remoteClientManager_->GetBundleManager()) {
2464         HILOG_ERROR("GetBundleManager fail");
2465         return false;
2466     }
2467     return true;
2468 }
2469 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)2470 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
2471 {
2472     if (appRecord == nullptr) {
2473         HILOG_ERROR("Restart resident process failed, the appRecord is nullptr.");
2474         return;
2475     }
2476     struct timespec t;
2477     t.tv_sec = 0;
2478     t.tv_nsec = 0;
2479     clock_gettime(CLOCK_MONOTONIC, &t);
2480     appRecord->SetRestartTimeMillis(static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS));
2481     appRecord->DecRestartResidentProcCount();
2482 
2483     auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
2484         return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
2485     };
2486     auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(), findRestartResidentTask);
2487     if (findIter != restartResedentTaskList_.end()) {
2488         restartResedentTaskList_.erase(findIter);
2489     }
2490 
2491     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
2492         HILOG_ERROR("restart resident process failed!");
2493         return;
2494     }
2495 
2496     auto bundleMgr = remoteClientManager_->GetBundleManager();
2497     BundleInfo bundleInfo;
2498     auto callerUid = IPCSkeleton::GetCallingUid();
2499     auto userId = GetUserIdByUid(callerUid);
2500     if (!IN_PROCESS_CALL(
2501         bundleMgr->GetBundleInfo(appRecord->GetBundleName(), BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
2502         HILOG_ERROR("GetBundleInfo fail");
2503         return;
2504     }
2505     std::vector<BundleInfo> infos;
2506     infos.emplace_back(bundleInfo);
2507     HILOG_INFO("the resident process [%{public}s] remaining restarts num is [%{public}d]",
2508         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
2509     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount(), appRecord->IsEmptyKeepAliveApp());
2510 }
2511 
NotifyAppStatus(const std::string & bundleName,const std::string & eventData)2512 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData)
2513 {
2514     HILOG_INFO("%{public}s called, bundle name is %{public}s, event is %{public}s",
2515         __func__, bundleName.c_str(), eventData.c_str());
2516     Want want;
2517     want.SetAction(eventData);
2518     ElementName element;
2519     element.SetBundleName(bundleName);
2520     want.SetElement(element);
2521     want.SetParam(Constants::USER_ID, 0);
2522     EventFwk::CommonEventData commonData {want};
2523     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
2524 }
2525 
NotifyAppStatusByCallerUid(const std::string & bundleName,const int32_t userId,const int32_t callerUid,const std::string & eventData)2526 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t userId,
2527     const int32_t callerUid, const std::string &eventData)
2528 {
2529     HILOG_INFO("%{public}s called, bundle name is %{public}s, , userId is %{public}d, event is %{public}s",
2530         __func__, bundleName.c_str(), userId, eventData.c_str());
2531     Want want;
2532     want.SetAction(eventData);
2533     ElementName element;
2534     element.SetBundleName(bundleName);
2535     want.SetElement(element);
2536     want.SetParam(Constants::USER_ID, userId);
2537     want.SetParam(Constants::UID, callerUid);
2538     EventFwk::CommonEventData commonData {want};
2539     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
2540 }
2541 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)2542 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(
2543     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
2544 {
2545     CHECK_CALLER_IS_SYSTEM_APP;
2546     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterApplicationStateObserver(
2547         observer, bundleNameList);
2548 }
2549 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)2550 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
2551 {
2552     CHECK_CALLER_IS_SYSTEM_APP;
2553     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterApplicationStateObserver(observer);
2554 }
2555 
GetForegroundApplications(std::vector<AppStateData> & list)2556 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
2557 {
2558     HILOG_DEBUG("begin.");
2559     CHECK_CALLER_IS_SYSTEM_APP;
2560     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2561     if (!isPerm) {
2562         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2563         return ERR_PERMISSION_DENIED;
2564     }
2565 
2566     appRunningManager_->GetForegroundApplications(list);
2567     return ERR_OK;
2568 }
2569 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)2570 int AppMgrServiceInner::StartUserTestProcess(
2571     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
2572 {
2573     HILOG_INFO("Enter");
2574     if (!observer) {
2575         HILOG_ERROR("observer nullptr.");
2576         return ERR_INVALID_VALUE;
2577     }
2578     if (!appRunningManager_) {
2579         HILOG_ERROR("appRunningManager_ is nullptr");
2580         return ERR_INVALID_VALUE;
2581     }
2582 
2583     std::string bundleName = want.GetStringParam("-b");
2584     if (bundleName.empty()) {
2585         HILOG_ERROR("Invalid bundle name");
2586         return ERR_INVALID_VALUE;
2587     }
2588 
2589     if (KillApplicationByUserIdLocked(bundleName, userId)) {
2590         HILOG_ERROR("Failed to kill the application");
2591         return ERR_INVALID_VALUE;
2592     }
2593 
2594     HapModuleInfo hapModuleInfo;
2595     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
2596         HILOG_ERROR("Failed to get HapModuleInfo for TestRunner");
2597         return ERR_INVALID_VALUE;
2598     }
2599 
2600     std::string processName;
2601     MakeProcessName(std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo, processName);
2602     HILOG_INFO("processName = [%{public}s]", processName.c_str());
2603 
2604     // Inspection records
2605     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
2606         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
2607     if (appRecord) {
2608         HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
2609         return ERR_INVALID_VALUE;
2610     }
2611 
2612     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
2613 }
2614 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)2615 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2616     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
2617 {
2618     HILOG_INFO("Enter");
2619     if (!observer) {
2620         HILOG_ERROR("observer nullptr.");
2621         return ERR_INVALID_VALUE;
2622     }
2623 
2624     bool moduleJson = false;
2625     if (!bundleInfo.hapModuleInfos.empty()) {
2626         moduleJson = bundleInfo.hapModuleInfos.back().isModuleJson;
2627     }
2628     if (moduleJson) {
2629         std::string moduleName = want.GetStringParam("-m");
2630         if (moduleName.empty()) {
2631             UserTestAbnormalFinish(observer, "No module name is specified.");
2632             return ERR_INVALID_VALUE;
2633         }
2634 
2635         bool found = false;
2636         for (auto item : bundleInfo.hapModuleInfos) {
2637             if (item.moduleName == moduleName) {
2638                 hapModuleInfo = item;
2639                 found = true;
2640                 break;
2641             }
2642         }
2643         if (!found) {
2644             UserTestAbnormalFinish(observer, "The specified module name is not found.");
2645             return ERR_INVALID_VALUE;
2646         }
2647     }
2648     return ERR_OK;
2649 }
2650 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)2651 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
2652 {
2653     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
2654     if (!observerProxy) {
2655         HILOG_ERROR("Failed to get ITestObserver proxy");
2656         return ERR_INVALID_VALUE;
2657     }
2658     observerProxy->TestFinished(msg, -1);
2659     return ERR_OK;
2660 }
2661 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)2662 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2663     const BundleInfo &info, const std::string &processName, const int userId)
2664 {
2665     HILOG_INFO("enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
2666     if (!CheckRemoteClient() || !appRunningManager_) {
2667         HILOG_ERROR("Failed to start the process being tested!");
2668         return ERR_INVALID_VALUE;
2669     }
2670 
2671     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name);
2672     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
2673     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
2674     if (!appRecord) {
2675         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
2676         return ERR_INVALID_VALUE;
2677     }
2678 
2679     auto isDebug = want.GetBoolParam("debugApp", false);
2680     HILOG_INFO("Set Debug : %{public}s", (isDebug ? "true" : "false"));
2681     appRecord->SetDebugApp(isDebug);
2682     if (want.GetBoolParam(COLD_START, false)) {
2683         appRecord->SetDebugApp(true);
2684     }
2685 
2686     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
2687     if (!testRecord) {
2688         HILOG_ERROR("Failed to make UserTestRecord!");
2689         return ERR_INVALID_VALUE;
2690     }
2691     testRecord->want = want;
2692     testRecord->observer = observer;
2693     testRecord->isFinished = false;
2694     testRecord->userId = userId;
2695     appRecord->SetUserTestInfo(testRecord);
2696 
2697     int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2698     uint32_t startFlags = 0x0;
2699     if (info.applicationInfo.debug) {
2700         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
2701     }
2702     StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, appInfo->bundleName,
2703         bundleIndex, appExistFlag);
2704 
2705     // If it is empty, the startup failed
2706     if (!appRecord) {
2707         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
2708         return ERR_INVALID_VALUE;
2709     }
2710 
2711     appRecord->SetTaskHandler(taskHandler_);
2712     appRecord->SetEventHandler(eventHandler_);
2713     appRecord->AddModules(appInfo, info.hapModuleInfos);
2714     HILOG_INFO("StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid());
2715 
2716     return ERR_OK;
2717 }
2718 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName,const pid_t & pid)2719 int AppMgrServiceInner::FinishUserTest(
2720     const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid)
2721 {
2722     HILOG_INFO("Enter");
2723     if (bundleName.empty()) {
2724         HILOG_ERROR("Invalid bundle name.");
2725         return ERR_INVALID_VALUE;
2726     }
2727     auto appRecord = GetAppRunningRecordByPid(pid);
2728     if (!appRecord) {
2729         HILOG_ERROR("no such appRecord");
2730         return ERR_INVALID_VALUE;
2731     }
2732 
2733     auto userTestRecord = appRecord->GetUserTestInfo();
2734     if (!userTestRecord) {
2735         HILOG_ERROR("unstart user test");
2736         return ERR_INVALID_VALUE;
2737     }
2738 
2739     FinishUserTestLocked(msg, resultCode, appRecord);
2740 
2741     int ret = KillApplicationByUserIdLocked(bundleName, userTestRecord->userId);
2742     if (ret) {
2743         HILOG_ERROR("Failed to kill process.");
2744         return ret;
2745     }
2746 
2747     return ERR_OK;
2748 }
2749 
FinishUserTestLocked(const std::string & msg,const int64_t & resultCode,const std::shared_ptr<AppRunningRecord> & appRecord)2750 int AppMgrServiceInner::FinishUserTestLocked(
2751     const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord)
2752 {
2753     HILOG_INFO("Enter");
2754     if (!appRecord) {
2755         HILOG_ERROR("Invalid appRecord");
2756         return ERR_INVALID_VALUE;
2757     }
2758 
2759     std::lock_guard<ffrt::mutex> lock(userTestLock_);
2760     auto userTestRecord = appRecord->GetUserTestInfo();
2761     if (!userTestRecord) {
2762         HILOG_WARN("not start user test");
2763         return ERR_INVALID_VALUE;
2764     }
2765     if (!userTestRecord->isFinished) {
2766         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
2767         if (!observerProxy) {
2768             HILOG_ERROR("Failed to get ITestObserver proxy");
2769             return ERR_INVALID_VALUE;
2770         }
2771         observerProxy->TestFinished(msg, resultCode);
2772 
2773         userTestRecord->isFinished = true;
2774     }
2775 
2776     return ERR_OK;
2777 }
2778 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo)2779 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)
2780 {
2781     HILOG_DEBUG("Start specified ability.");
2782     if (!CheckRemoteClient()) {
2783         return;
2784     }
2785 
2786     BundleInfo bundleInfo;
2787     HapModuleInfo hapModuleInfo;
2788     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
2789 
2790     int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2791     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
2792         return;
2793     }
2794 
2795     std::string processName;
2796     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
2797     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, processName);
2798 
2799     std::vector<HapModuleInfo> hapModules;
2800     hapModules.emplace_back(hapModuleInfo);
2801 
2802     std::shared_ptr<AppRunningRecord> appRecord;
2803     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
2804     if (!appRecord) {
2805         bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
2806         // new app record
2807         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
2808         if (!appRecord) {
2809             HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2810             return;
2811         }
2812         auto wantPtr = std::make_shared<AAFwk::Want>(want);
2813         if (wantPtr != nullptr) {
2814             appRecord->SetCallerPid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
2815             appRecord->SetCallerUid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
2816             appRecord->SetCallerTokenId(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
2817         }
2818         appRecord->SetProcessAndExtensionType(abilityInfoPtr);
2819         appRecord->SetTaskHandler(taskHandler_);
2820         appRecord->SetEventHandler(eventHandler_);
2821         appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
2822             AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT);
2823         uint32_t startFlags = BuildStartFlags(want, abilityInfo);
2824         int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2825         StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, appInfo->bundleName,
2826             bundleIndex, appExistFlag);
2827 
2828         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2829         appRecord->AddModules(appInfo, hapModules);
2830     } else {
2831         HILOG_DEBUG("process is exist");
2832         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2833         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
2834         if (!moduleRecord) {
2835             HILOG_DEBUG("module record is nullptr, add modules");
2836             appRecord->AddModules(appInfo, hapModules);
2837             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
2838         } else {
2839             HILOG_DEBUG("schedule accept want");
2840             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
2841         }
2842     }
2843 }
2844 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)2845 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
2846 {
2847     if (!response) {
2848         HILOG_ERROR("response is nullptr, register failed.");
2849         return;
2850     }
2851 
2852     pid_t callingPid = IPCSkeleton::GetCallingPid();
2853     pid_t pid = getpid();
2854     if (callingPid != pid) {
2855         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
2856         return;
2857     }
2858 
2859     startSpecifiedAbilityResponse_ = response;
2860 }
2861 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)2862 void AppMgrServiceInner::ScheduleAcceptWantDone(
2863     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
2864 {
2865     HILOG_DEBUG("Schedule accept want done, flag: %{public}s", flag.c_str());
2866 
2867     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
2868     if (!appRecord) {
2869         HILOG_ERROR("Get app record failed.");
2870         return;
2871     }
2872     appRecord->ScheduleAcceptWantDone();
2873 
2874     if (startSpecifiedAbilityResponse_) {
2875         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag);
2876     }
2877 }
2878 
HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)2879 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)
2880 {
2881     HILOG_DEBUG("called start specified ability time out!");
2882     if (!appRunningManager_) {
2883         HILOG_ERROR("appRunningManager_ is nullptr");
2884         return;
2885     }
2886 
2887     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2888     if (!appRecord) {
2889         HILOG_ERROR("appRecord is nullptr");
2890         return;
2891     }
2892 
2893     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
2894         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
2895     }
2896 
2897     KillApplicationByRecord(appRecord);
2898 }
2899 
UpdateConfiguration(const Configuration & config)2900 int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config)
2901 {
2902     if (!appRunningManager_) {
2903         HILOG_ERROR("appRunningManager_ is null");
2904         return ERR_INVALID_VALUE;
2905     }
2906     CHECK_CALLER_IS_SYSTEM_APP;
2907 
2908     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
2909     if (ret != ERR_OK) {
2910         return ret;
2911     }
2912 
2913     std::vector<std::string> changeKeyV;
2914     configuration_->CompareDifferent(changeKeyV, config);
2915     HILOG_INFO("changeKeyV size :%{public}zu", changeKeyV.size());
2916     if (changeKeyV.empty()) {
2917         HILOG_ERROR("changeKeyV is empty");
2918         return ERR_INVALID_VALUE;
2919     }
2920     configuration_->Merge(changeKeyV, config);
2921     // all app
2922     int32_t result = appRunningManager_->UpdateConfiguration(config);
2923     if (result != ERR_OK) {
2924         HILOG_ERROR("update error, not notify");
2925         return result;
2926     }
2927     // notify
2928     std::lock_guard<ffrt::mutex> notifyLock(configurationObserverLock_);
2929     for (auto &observer : configurationObservers_) {
2930         if (observer != nullptr) {
2931             observer->OnConfigurationUpdated(config);
2932         }
2933     }
2934     return result;
2935 }
2936 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)2937 int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
2938 {
2939     HILOG_INFO("AppMgrServiceInner::RegisterConfigurationObserver: called");
2940 
2941     if (observer == nullptr) {
2942         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
2943         return ERR_INVALID_VALUE;
2944     }
2945     std::lock_guard<ffrt::mutex> registerLock(configurationObserverLock_);
2946     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
2947         [&observer](const sptr<IConfigurationObserver> &item) {
2948             return (item && item->AsObject() == observer->AsObject());
2949         }
2950     );
2951     if (it != configurationObservers_.end()) {
2952         HILOG_ERROR("AppMgrServiceInner::Register error: observer exist");
2953         return ERR_INVALID_VALUE;
2954     }
2955     configurationObservers_.push_back(observer);
2956     return NO_ERROR;
2957 }
2958 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)2959 int32_t AppMgrServiceInner::UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
2960 {
2961     HILOG_INFO("AppMgrServiceInner::UnregisterConfigurationObserver: called");
2962     if (observer == nullptr) {
2963         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
2964         return ERR_INVALID_VALUE;
2965     }
2966     std::lock_guard<ffrt::mutex> unregisterLock(configurationObserverLock_);
2967     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
2968         [&observer](const sptr<IConfigurationObserver> &item) {
2969             return (item && item->AsObject() == observer->AsObject());
2970         }
2971     );
2972     if (it != configurationObservers_.end()) {
2973         configurationObservers_.erase(it);
2974         return NO_ERROR;
2975     }
2976     HILOG_INFO("AppMgrServiceInner ConfigurationObserver not register");
2977     return ERR_INVALID_VALUE;
2978 }
2979 
InitGlobalConfiguration()2980 void AppMgrServiceInner::InitGlobalConfiguration()
2981 {
2982     if (!configuration_) {
2983         HILOG_ERROR("configuration_ is null");
2984         return;
2985     }
2986 
2987 #ifdef SUPPORT_GRAPHICS
2988     // Currently only this interface is known
2989     auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
2990     HILOG_INFO("current global language is : %{public}s", language.c_str());
2991     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
2992 #endif
2993 
2994     // Assign to default colorMode "light"
2995     HILOG_INFO("current global colorMode is : %{public}s", ConfigurationInner::COLOR_MODE_LIGHT);
2996     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
2997 
2998     // Get input pointer device
2999     std::string hasPointerDevice = system::GetParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "false");
3000     HILOG_INFO("current hasPointerDevice is %{public}s", hasPointerDevice.c_str());
3001     configuration_->AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, hasPointerDevice);
3002 
3003     // Get DeviceType
3004     auto deviceType = GetDeviceType();
3005     HILOG_INFO("current deviceType is %{public}s", deviceType);
3006     configuration_->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType);
3007 }
3008 
GetConfiguration()3009 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
3010 {
3011     return configuration_;
3012 }
3013 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)3014 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
3015 {
3016     HILOG_DEBUG("Kill application by appRecord.");
3017     if (!appRecord || !taskHandler_) {
3018         HILOG_WARN("appRecord or taskHandler_ is nullptr.");
3019         return;
3020     }
3021 
3022     auto pid = appRecord->GetPriorityObject()->GetPid();
3023     appRecord->SetTerminating();
3024     appRecord->ScheduleProcessSecurityExit();
3025 
3026     auto startTime = SystemTimeMillisecond();
3027     std::list<pid_t> pids = {pid};
3028     if (WaitForRemoteProcessExit(pids, startTime)) {
3029         HILOG_INFO("The remote process exited successfully");
3030         return;
3031     }
3032 
3033     auto timeoutTask = [pid, innerService = shared_from_this()]() {
3034         HILOG_INFO("KillProcessByPid %{public}d", pid);
3035         int32_t result = innerService->KillProcessByPid(pid);
3036         if (result < 0) {
3037             HILOG_ERROR("Kill application by app record failed, pid: %{public}d", pid);
3038             return;
3039         }
3040     };
3041     taskHandler_->SubmitTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
3042 }
3043 
SendHiSysEvent(const int32_t innerEventId,const int64_t eventId)3044 void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_t eventId)
3045 {
3046     HILOG_DEBUG("called AppMgrServiceInner SendHiSysEvent!");
3047     if (!appRunningManager_) {
3048         HILOG_ERROR("appRunningManager_ is nullptr");
3049         return;
3050     }
3051 
3052     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
3053     if (!appRecord) {
3054         HILOG_ERROR("appRecord is nullptr");
3055         return;
3056     }
3057     const int bufferLen = 128;
3058     char paramOutBuf[bufferLen] = {0};
3059     const char *hook_mode = "startup:";
3060     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
3061     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
3062         HILOG_DEBUG("SendHiSysEvent, Hook_mode: no handle time out");
3063         return;
3064     }
3065 
3066     std::string eventName = AppExecFwk::AppFreezeType::LIFECYCLE_TIMEOUT;
3067     int32_t pid = appRecord->GetPriorityObject()->GetPid();
3068     int32_t uid = appRecord->GetUid();
3069     std::string packageName = appRecord->GetBundleName();
3070     std::string processName = appRecord->GetProcessName();
3071     std::string msg = AppExecFwk::AppFreezeType::APP_LIFECYCLE_TIMEOUT;
3072     msg += ",";
3073     int typeId = AppExecFwk::AppfreezeManager::TypeAttribute::NORMAL_TIMEOUT;
3074     switch (innerEventId) {
3075         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
3076             msg += EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
3077             break;
3078         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
3079             msg += EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
3080             break;
3081         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
3082             msg += EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
3083             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3084             break;
3085         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
3086             msg += EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
3087             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3088             break;
3089         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
3090             msg += EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
3091             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
3092             break;
3093         default:
3094             msg += EVENT_MESSAGE_DEFAULT;
3095             break;
3096     }
3097 
3098     HILOG_WARN("LIFECYCLE_TIMEOUT, eventName = %{public}s, uid = %{public}d, pid = %{public}d, \
3099         packageName = %{public}s, processName = %{public}s, msg = %{public}s",
3100         eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
3101     AppExecFwk::AppfreezeManager::GetInstance()->LifecycleTimeoutHandle(
3102         typeId, pid, eventName, packageName, msg);
3103 }
3104 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)3105 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
3106 {
3107     auto appRecord = GetAppRunningRecordByPid(pid);
3108     if (!appRecord) {
3109         HILOG_ERROR("no such appRecord");
3110         return ERR_NAME_NOT_FOUND;
3111     }
3112 
3113     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3114     auto callingPid = IPCSkeleton::GetCallingPid();
3115     if (!isSaCall && callingPid != pid) {
3116         HILOG_ERROR("Permission verify failed.");
3117         return ERR_PERMISSION_DENIED;
3118     }
3119     for (auto &item : appRecord->GetAbilities()) {
3120         tokens.emplace_back(item.first);
3121     }
3122     return ERR_OK;
3123 }
3124 
GetApplicationInfoByProcessID(const int pid,AppExecFwk::ApplicationInfo & application,bool & debug)3125 int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application,
3126     bool &debug)
3127 {
3128     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3129     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
3130     if (!isSaCall && !isShellCall) {
3131         HILOG_ERROR("no permissions.");
3132         return ERR_PERMISSION_DENIED;
3133     }
3134     auto appRecord = GetAppRunningRecordByPid(pid);
3135     if (!appRecord) {
3136         HILOG_ERROR("no such appRecord for PID:%{public}d", pid);
3137         return ERR_NAME_NOT_FOUND;
3138     }
3139 
3140     auto info = appRecord->GetApplicationInfo();
3141     if (info == nullptr) {
3142         HILOG_ERROR("ApplicationInfo is nullptr !");
3143         return ERR_NO_INIT;
3144     }
3145     application = *info;
3146     debug = appRecord->IsDebugApp();
3147     return ERR_OK;
3148 }
3149 
VerifyProcessPermission() const3150 int AppMgrServiceInner::VerifyProcessPermission() const
3151 {
3152     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3153     if (isSaCall) {
3154         return ERR_OK;
3155     }
3156 
3157     if (VerifyAPL()) {
3158         return ERR_OK;
3159     }
3160 
3161     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3162         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
3163     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
3164 }
3165 
VerifyProcessPermission(const std::string & bundleName) const3166 int AppMgrServiceInner::VerifyProcessPermission(const std::string &bundleName) const
3167 {
3168     CHECK_CALLER_IS_SYSTEM_APP;
3169     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3170     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
3171     if (isSaCall || isShellCall) {
3172         return ERR_OK;
3173     }
3174 
3175     if (VerifyAPL()) {
3176         return ERR_OK;
3177     }
3178 
3179     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3180         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
3181     if (isCallingPerm) {
3182         if (AAFwk::PermissionVerification::GetInstance()->IsGatewayCall()) {
3183             return ERR_OK;
3184         }
3185         auto callerPid = IPCSkeleton::GetCallingPid();
3186         auto appRecord = GetAppRunningRecordByPid(callerPid);
3187         if (!appRecord || appRecord->GetBundleName() != bundleName) {
3188             HILOG_ERROR("Permission verification failed.");
3189             return ERR_PERMISSION_DENIED;
3190         }
3191     } else {
3192         HILOG_ERROR("Permission verification failed.");
3193         return ERR_PERMISSION_DENIED;
3194     }
3195 
3196     return ERR_OK;
3197 }
3198 
VerifyProcessPermission(const sptr<IRemoteObject> & token) const3199 int AppMgrServiceInner::VerifyProcessPermission(const sptr<IRemoteObject> &token) const
3200 {
3201     CHECK_CALLER_IS_SYSTEM_APP;
3202     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3203     if (isSaCall) {
3204         return ERR_OK;
3205     }
3206 
3207     if (VerifyAPL()) {
3208         return ERR_OK;
3209     }
3210 
3211     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3212         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
3213     if (isCallingPerm) {
3214         if (AAFwk::PermissionVerification::GetInstance()->IsGatewayCall()) {
3215             return ERR_OK;
3216         }
3217         auto callerUid = IPCSkeleton::GetCallingUid();
3218         auto appRecord = GetAppRunningRecordByAbilityToken(token);
3219         if (!appRecord || appRecord->GetUid() != callerUid) {
3220             HILOG_ERROR("Permission verification failed.");
3221             return ERR_PERMISSION_DENIED;
3222         }
3223     } else {
3224         HILOG_ERROR("Permission verification failed.");
3225         return ERR_PERMISSION_DENIED;
3226     }
3227 
3228     return ERR_OK;
3229 }
3230 
VerifyAPL() const3231 bool AppMgrServiceInner::VerifyAPL() const
3232 {
3233     if (!appRunningManager_) {
3234         HILOG_ERROR("appRunningManager_ is nullptr");
3235         return false;
3236     }
3237 
3238     auto callerPid = IPCSkeleton::GetCallingPid();
3239     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
3240     if (!appRecord) {
3241         HILOG_ERROR("Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
3242         return false;
3243     }
3244 
3245     auto applicationInfo = appRecord->GetApplicationInfo();
3246     if (!applicationInfo) {
3247         HILOG_ERROR("Get application info failed.");
3248         return false;
3249     }
3250 
3251     auto apl = applicationInfo->appPrivilegeLevel;
3252     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
3253         HILOG_ERROR("caller is not system_basic or system_core.");
3254         return false;
3255     }
3256     return true;
3257 }
3258 
VerifyAccountPermission(const std::string & permissionName,const int userId) const3259 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId) const
3260 {
3261     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3262     if (isSaCall) {
3263         return ERR_OK;
3264     }
3265 
3266     if (userId != currentUserId_) {
3267         auto isCallingPermAccount = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3268             AAFwk::PermissionConstants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
3269         if (!isCallingPermAccount) {
3270             HILOG_ERROR("%{public}s: Permission accounts verification failed", __func__);
3271             return ERR_PERMISSION_DENIED;
3272         }
3273     }
3274     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(permissionName);
3275     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
3276 }
3277 
VerifyRequestPermission() const3278 int AppMgrServiceInner::VerifyRequestPermission() const
3279 {
3280     auto callerUid = IPCSkeleton::GetCallingUid();
3281 
3282     if (callerUid == ROOT_UID || callerUid == FOUNDATION_UID) {
3283         return ERR_OK;
3284     } else {
3285         HILOG_ERROR("Permission verification failed, callerUid: %{public}d", callerUid);
3286         return ERR_PERMISSION_DENIED;
3287     }
3288 }
3289 
PreStartNWebSpawnProcess(const pid_t hostPid)3290 int AppMgrServiceInner::PreStartNWebSpawnProcess(const pid_t hostPid)
3291 {
3292     HILOG_INFO("AppMgrServiceInner::PreStartNWebSpawnProcess");
3293     if (hostPid <= 0) {
3294         HILOG_ERROR("invalid param, hostPid:%{public}d", hostPid);
3295         return ERR_INVALID_VALUE;
3296     }
3297 
3298     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
3299     if (!nwebSpawnClient) {
3300         HILOG_ERROR("nwebSpawnClient is null");
3301         return ERR_INVALID_VALUE;
3302     }
3303 
3304     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(hostPid);
3305     if (!appRecord) {
3306         HILOG_ERROR("no such app Record, pid:%{public}d", hostPid);
3307         return ERR_INVALID_VALUE;
3308     }
3309 
3310     ErrCode errCode = nwebSpawnClient->PreStartNWebSpawnProcess();
3311     if (FAILED(errCode)) {
3312         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
3313         return ERR_INVALID_VALUE;
3314     }
3315 
3316     return 0;
3317 }
3318 
StartRenderProcess(const pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,int32_t crashFd,pid_t & renderPid)3319 int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam,
3320     int32_t ipcFd, int32_t sharedFd, int32_t crashFd, pid_t &renderPid)
3321 {
3322     HILOG_INFO("start render process, hostPid:%{public}d", hostPid);
3323     if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 ||
3324         crashFd <= 0) {
3325         HILOG_ERROR("invalid param: hostPid:%{public}d renderParam:%{private}s "
3326                     "ipcFd:%{public}d  crashFd:%{public}d sharedFd:%{public}d",
3327                     hostPid, renderParam.c_str(), ipcFd, crashFd, sharedFd);
3328         return ERR_INVALID_VALUE;
3329     }
3330 
3331     if (!appRunningManager_) {
3332         HILOG_ERROR("appRunningManager_ is nullptr, not start render process");
3333         return ERR_INVALID_VALUE;
3334     }
3335 
3336     auto appRecord = GetAppRunningRecordByPid(hostPid);
3337     if (!appRecord) {
3338         HILOG_ERROR("no such appRecord, hostPid:%{public}d", hostPid);
3339         return ERR_INVALID_VALUE;
3340     }
3341 
3342     auto renderRecordMap = appRecord->GetRenderRecordMap();
3343     if (!renderRecordMap.empty() && deviceType_.compare("tablet") != 0 && deviceType_.compare("pc") != 0 &&
3344         deviceType_.compare("2in1") != 0) {
3345         for (auto iter : renderRecordMap) {
3346             if (iter.second != nullptr) {
3347                 renderPid = iter.second->GetPid();
3348                 if (ProcessExist(renderPid)) {
3349                     HILOG_WARN("already exist render process,do not request again, renderPid:%{public}d", renderPid);
3350                     return ERR_ALREADY_EXIST_RENDER;
3351                 }
3352                 auto scheduler = iter.second->GetScheduler();
3353                 if (scheduler) {
3354                     HILOG_WARN("render process not realy exist, renderPid:%{public}d", renderPid);
3355                     OnRenderRemoteDied(scheduler->AsObject());
3356                 }
3357             }
3358         }
3359     }
3360 
3361     auto renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam, ipcFd, sharedFd, crashFd, appRecord);
3362     if (!renderRecord) {
3363         HILOG_ERROR("create render record failed, hostPid:%{public}d", hostPid);
3364         return ERR_INVALID_VALUE;
3365     }
3366 
3367     return StartRenderProcessImpl(renderRecord, appRecord, renderPid);
3368 }
3369 
AttachRenderProcess(const pid_t pid,const sptr<IRenderScheduler> & scheduler)3370 void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler)
3371 {
3372     HILOG_DEBUG("attach render process start");
3373     if (pid <= 0) {
3374         HILOG_ERROR("invalid render process pid:%{public}d", pid);
3375         return;
3376     }
3377     if (!scheduler) {
3378         HILOG_ERROR("render scheduler is null");
3379         return;
3380     }
3381 
3382     if (!appRunningManager_) {
3383         HILOG_ERROR("appRunningManager_ is null");
3384         return;
3385     }
3386 
3387     HILOG_INFO("attach render process pid:%{public}d", pid);
3388     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
3389     if (!appRecord) {
3390         HILOG_ERROR("no such app Record, pid:%{public}d", pid);
3391         return;
3392     }
3393 
3394     auto renderRecord = appRecord->GetRenderRecordByPid(pid);
3395     if (!renderRecord) {
3396         HILOG_ERROR("no such render Record, pid:%{public}d", pid);
3397         return;
3398     }
3399 
3400     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
3401     appDeathRecipient->SetTaskHandler(taskHandler_);
3402     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
3403     appDeathRecipient->SetIsRenderProcess(true);
3404     renderRecord->SetScheduler(scheduler);
3405     renderRecord->SetDeathRecipient(appDeathRecipient);
3406     renderRecord->RegisterDeathRecipient();
3407 
3408     // notify fd to render process
3409     scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(),
3410                                renderRecord->GetSharedFd(),
3411                                renderRecord->GetCrashFd());
3412 }
3413 
GenerateRenderUid(int32_t & renderUid)3414 bool AppMgrServiceInner::GenerateRenderUid(int32_t &renderUid)
3415 {
3416     std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
3417     int32_t uid = lastRenderUid_ + 1;
3418     bool needSecondScan = true;
3419     if (uid > Constants::END_UID_FOR_RENDER_PROCESS) {
3420         uid = Constants::START_UID_FOR_RENDER_PROCESS;
3421         needSecondScan = false;
3422     }
3423 
3424     if (renderUidSet_.empty()) {
3425         renderUid = uid;
3426         renderUidSet_.insert(renderUid);
3427         lastRenderUid_ = renderUid;
3428         return true;
3429     }
3430 
3431     for (int32_t i = uid; i <= Constants::END_UID_FOR_RENDER_PROCESS; i++) {
3432         if (renderUidSet_.find(i) == renderUidSet_.end()) {
3433             renderUid = i;
3434             renderUidSet_.insert(renderUid);
3435             lastRenderUid_ = renderUid;
3436             return true;
3437         }
3438     }
3439 
3440     if (needSecondScan) {
3441         for (int32_t i = Constants::START_UID_FOR_RENDER_PROCESS; i <= lastRenderUid_; i++) {
3442             if (renderUidSet_.find(i) == renderUidSet_.end()) {
3443                 renderUid = i;
3444                 renderUidSet_.insert(renderUid);
3445                 lastRenderUid_ = renderUid;
3446                 return true;
3447             }
3448         }
3449     }
3450 
3451     return false;
3452 }
3453 
StartRenderProcessImpl(const std::shared_ptr<RenderRecord> & renderRecord,const std::shared_ptr<AppRunningRecord> appRecord,pid_t & renderPid)3454 int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
3455     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid)
3456 {
3457     if (!renderRecord || !appRecord) {
3458         HILOG_ERROR("renderRecord or appRecord is nullptr.");
3459         return ERR_INVALID_VALUE;
3460     }
3461 
3462     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
3463     if (!nwebSpawnClient) {
3464         HILOG_ERROR("nwebSpawnClient is null");
3465         return ERR_INVALID_VALUE;
3466     }
3467 
3468     int32_t renderUid = Constants::INVALID_UID;
3469     if (!GenerateRenderUid(renderUid)) {
3470         HILOG_ERROR("Generate renderUid failed");
3471         return ERR_INVALID_OPERATION;
3472     }
3473 
3474     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
3475     startMsg.renderParam = renderRecord->GetRenderParam();
3476     startMsg.uid = renderUid;
3477     startMsg.gid = renderUid;
3478     startMsg.code = 0; // 0: DEFAULT
3479     pid_t pid = 0;
3480     ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid);
3481     if (FAILED(errCode)) {
3482         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
3483         std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
3484         renderUidSet_.erase(renderUid);
3485         return ERR_INVALID_VALUE;
3486     }
3487     renderPid = pid;
3488     renderRecord->SetPid(pid);
3489     renderRecord->SetUid(renderUid);
3490     appRecord->AddRenderRecord(renderRecord);
3491     HILOG_INFO("start render process success, hostPid:%{public}d, hostUid:%{public}d, pid:%{public}d, uid:%{public}d",
3492         renderRecord->GetHostPid(), renderRecord->GetHostUid(), pid, renderUid);
3493     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessCreated(renderRecord);
3494     return 0;
3495 }
3496 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)3497 int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
3498 {
3499     if (remoteClientManager_ == nullptr) {
3500         HILOG_ERROR("remoteClientManager_ is null");
3501         return ERR_INVALID_VALUE;
3502     }
3503     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
3504     if (!nwebSpawnClient) {
3505         HILOG_ERROR("nwebSpawnClient is null");
3506         return ERR_INVALID_VALUE;
3507     }
3508 
3509     AppSpawnStartMsg startMsg;
3510     startMsg.pid = renderPid;
3511     startMsg.code = 1; // 1: GET_RENDER_TERMINATION_STATUS
3512     ErrCode errCode = nwebSpawnClient->GetRenderProcessTerminationStatus(startMsg, status);
3513     if (FAILED(errCode)) {
3514         HILOG_ERROR("failed to get render process termination status, errCode %{public}08x", errCode);
3515         return ERR_INVALID_VALUE;
3516     }
3517     HILOG_DEBUG("Get render process termination status success, renderPid:%{public}d, status:%{public}d",
3518         renderPid, status);
3519     return 0;
3520 }
3521 
OnRenderRemoteDied(const wptr<IRemoteObject> & remote)3522 void AppMgrServiceInner::OnRenderRemoteDied(const wptr<IRemoteObject> &remote)
3523 {
3524     HILOG_ERROR("On render remote died.");
3525     if (appRunningManager_) {
3526         auto renderRecord = appRunningManager_->OnRemoteRenderDied(remote);
3527         if (renderRecord) {
3528             {
3529                 std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
3530                 renderUidSet_.erase(renderRecord->GetUid());
3531             }
3532             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
3533         }
3534     }
3535 }
3536 
BuildStartFlags(const AAFwk::Want & want,const AbilityInfo & abilityInfo)3537 uint32_t AppMgrServiceInner::BuildStartFlags(const AAFwk::Want &want, const AbilityInfo &abilityInfo)
3538 {
3539     uint32_t startFlags = 0x0;
3540     if (want.GetBoolParam("coldStart", false)) {
3541         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::COLD_START);
3542     }
3543 
3544     if (want.GetIntParam(DLP_PARAMS_INDEX, 0) != 0) {
3545         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DLP_MANAGER);
3546     }
3547 
3548     if (abilityInfo.extensionAbilityType == ExtensionAbilityType::BACKUP) {
3549         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::BACKUP_EXTENSION);
3550     }
3551 
3552     if (abilityInfo.applicationInfo.debug) {
3553         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
3554     }
3555     if (abilityInfo.applicationInfo.asanEnabled) {
3556 	    startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::ASANENABLED);
3557     }
3558     if (want.GetBoolParam("nativeDebug", false)) {
3559         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::NATIVEDEBUG);
3560     }
3561 
3562     return startFlags;
3563 }
3564 
AddWatchParameter()3565 void AppMgrServiceInner::AddWatchParameter()
3566 {
3567     HILOG_INFO("%{public}s called.", __func__);
3568     auto context = new (std::nothrow) std::weak_ptr<AppMgrServiceInner>(shared_from_this());
3569     int ret = WatchParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, PointerDeviceEventCallback,
3570         context);
3571     if (ret != 0) {
3572         HILOG_ERROR("watch parameter %{public}s failed with %{public}d.",
3573             AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, ret);
3574     }
3575 }
3576 
InitFocusListener()3577 void AppMgrServiceInner::InitFocusListener()
3578 {
3579     HILOG_INFO("begin initFocus listener.");
3580     if (focusListener_) {
3581         return;
3582     }
3583 
3584     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
3585     auto registerTask = [innerService = shared_from_this()]() {
3586         if (innerService) {
3587             HILOG_INFO("RegisterFocusListener task");
3588             innerService->RegisterFocusListener();
3589         }
3590     };
3591     if (taskHandler_) {
3592         taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
3593         HILOG_INFO("Submit RegisterFocusListenerTask");
3594     }
3595 }
3596 
RegisterFocusListener()3597 void AppMgrServiceInner::RegisterFocusListener()
3598 {
3599     HILOG_INFO("RegisterFocusListener begin");
3600     if (!focusListener_) {
3601         HILOG_ERROR("no focusListener_");
3602         return;
3603     }
3604     WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
3605     HILOG_INFO("RegisterFocusListener end");
3606 }
3607 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)3608 void AppMgrServiceInner::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
3609 {
3610     if (!focusChangeInfo) {
3611         HILOG_WARN("focused, invalid focusChangeInfo");
3612         return;
3613     }
3614     HILOG_DEBUG("focused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
3615 
3616     if (focusChangeInfo->pid_ <= 0) {
3617         HILOG_ERROR("invalid pid:%{public}d", focusChangeInfo->pid_);
3618         return;
3619     }
3620 
3621     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
3622     if (!appRecord) {
3623         HILOG_ERROR("focused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
3624         return;
3625     }
3626 
3627     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, true)) {
3628         HILOG_DEBUG("only change ability focus state, do not change process or application focus state.");
3629         return;
3630     }
3631 
3632     bool needNotifyApp = appRunningManager_->IsApplicationFirstFocused(*appRecord);
3633     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp);
3634     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
3635 }
3636 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)3637 void AppMgrServiceInner::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
3638 {
3639     if (!focusChangeInfo) {
3640         HILOG_WARN("unfocused, invalid focusChangeInfo");
3641         return;
3642     }
3643     HILOG_DEBUG("unfocused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
3644 
3645     if (focusChangeInfo->pid_ <= 0) {
3646         HILOG_ERROR("invalid pid:%{public}d", focusChangeInfo->pid_);
3647         return;
3648     }
3649 
3650     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
3651     if (!appRecord) {
3652         HILOG_ERROR("unfocused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
3653         return;
3654     }
3655 
3656     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, false)) {
3657         HILOG_DEBUG("only change ability from focus to unfocus, do not change process or application focus state.");
3658         return;
3659     }
3660 
3661     bool needNotifyApp = appRunningManager_->IsApplicationUnfocused(appRecord->GetBundleName());
3662     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp);
3663     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
3664 }
3665 
PointerDeviceEventCallback(const char * key,const char * value,void * context)3666 void AppMgrServiceInner::PointerDeviceEventCallback(const char *key, const char *value, void *context)
3667 {
3668     HILOG_INFO("%{public}s called.", __func__);
3669     auto weak = static_cast<std::weak_ptr<AppMgrServiceInner>*>(context);
3670     if (weak == nullptr) {
3671         HILOG_ERROR("context is nullptr.");
3672         return;
3673     }
3674 
3675     auto appMgrServiceInner = weak->lock();
3676     if (appMgrServiceInner == nullptr) {
3677         HILOG_ERROR("app manager service inner is nullptr.");
3678         return;
3679     }
3680 
3681     if ((strcmp(key, AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE) != 0) ||
3682         ((strcmp(value, "true") != 0) && (strcmp(value, "false") != 0))) {
3683         HILOG_ERROR("key %{public}s or value %{public}s mismatch.", key, value);
3684         return;
3685     }
3686 
3687     Configuration changeConfig;
3688     if (!changeConfig.AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, value)) {
3689         HILOG_ERROR("add %{public}s item to configuration failed.", key);
3690         return;
3691     }
3692 
3693     HILOG_DEBUG("update config %{public}s to %{public}s", key, value);
3694     auto result = appMgrServiceInner->UpdateConfiguration(changeConfig);
3695     if (result != 0) {
3696         HILOG_ERROR("update config failed with %{public}d, key: %{public}s, value: %{public}s.", result, key, value);
3697         return;
3698     }
3699 }
3700 
GetAppRunningStateByBundleName(const std::string & bundleName)3701 bool AppMgrServiceInner::GetAppRunningStateByBundleName(const std::string &bundleName)
3702 {
3703     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3704     HILOG_DEBUG("function called.");
3705     if (!appRunningManager_) {
3706         HILOG_ERROR("app running manager is nullptr.");
3707         return false;
3708     }
3709 
3710     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
3711         HILOG_ERROR("Permission deny, not SA.");
3712         return false;
3713     }
3714 
3715     return appRunningManager_->GetAppRunningStateByBundleName(bundleName);
3716 }
3717 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)3718 int32_t AppMgrServiceInner::NotifyLoadRepairPatch(const std::string &bundleName,
3719     const sptr<IQuickFixCallback> &callback)
3720 {
3721     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3722     HILOG_DEBUG("function called.");
3723     if (!appRunningManager_) {
3724         HILOG_ERROR("app running manager is nullptr.");
3725         return ERR_INVALID_OPERATION;
3726     }
3727 
3728     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
3729         HILOG_ERROR("Permission deny, not quick_fix.");
3730         return ERR_PERMISSION_DENIED;
3731     }
3732 
3733     return appRunningManager_->NotifyLoadRepairPatch(bundleName, callback);
3734 }
3735 
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)3736 int32_t AppMgrServiceInner::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
3737 {
3738     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3739     HILOG_DEBUG("function called.");
3740     if (!appRunningManager_) {
3741         HILOG_ERROR("app running manager is nullptr.");
3742         return ERR_INVALID_OPERATION;
3743     }
3744 
3745     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
3746         HILOG_ERROR("Permission deny, not quick_fix.");
3747         return ERR_PERMISSION_DENIED;
3748     }
3749 
3750     return appRunningManager_->NotifyHotReloadPage(bundleName, callback);
3751 }
3752 
3753 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
SetContinuousTaskProcess(int32_t pid,bool isContinuousTask)3754 int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask)
3755 {
3756     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3757     if (!isSaCall) {
3758         HILOG_ERROR("callerToken not SA %{public}s", __func__);
3759         return ERR_INVALID_VALUE;
3760     }
3761 
3762     if (!appRunningManager_) {
3763         HILOG_ERROR("app running manager is nullptr.");
3764         return ERR_INVALID_OPERATION;
3765     }
3766 
3767     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(pid);
3768     if (!appRecord) {
3769         HILOG_ERROR("Get app running record by pid failed. pid: %{public}d", pid);
3770         return false;
3771     }
3772     appRecord->SetContinuousTaskAppState(isContinuousTask);
3773     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
3774 
3775     return ERR_OK;
3776 }
3777 #endif
3778 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)3779 int32_t AppMgrServiceInner::NotifyUnLoadRepairPatch(const std::string &bundleName,
3780     const sptr<IQuickFixCallback> &callback)
3781 {
3782     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3783     HILOG_DEBUG("function called.");
3784     if (!appRunningManager_) {
3785         HILOG_ERROR("app running manager is nullptr.");
3786         return ERR_INVALID_OPERATION;
3787     }
3788 
3789     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
3790         HILOG_ERROR("Permission deny, not quick_fix.");
3791         return ERR_PERMISSION_DENIED;
3792     }
3793 
3794     return appRunningManager_->NotifyUnLoadRepairPatch(bundleName, callback);
3795 }
3796 
AppRecoveryNotifyApp(int32_t pid,const std::string & bundleName,FaultDataType faultType,const std::string & markers)3797 void AppMgrServiceInner::AppRecoveryNotifyApp(int32_t pid, const std::string& bundleName,
3798     FaultDataType faultType, const std::string& markers)
3799 {
3800     HILOG_INFO("AppRecovery NotifyApp to kill is: bundleName: %{public}s, faultType: %{public}d, pid: %{public}d",
3801         bundleName.c_str(), faultType, pid);
3802     if (faultType != FaultDataType::APP_FREEZE) {
3803         KillProcessByPid(pid);
3804         return;
3805     }
3806 
3807     std::string timeOutName = "waitSaveTask" + std::to_string(pid) + bundleName;
3808     if (markers == "appRecovery") {
3809         if (taskHandler_->CancelTask(timeOutName)) {
3810             KillProcessByPid(pid);
3811         }
3812         return;
3813     }
3814 
3815     if (markers != "recoveryTimeout") {
3816         return;
3817     }
3818     auto waitSaveTask = [pid, bundleName, innerService = shared_from_this()]() {
3819         auto appRecord = innerService->GetAppRunningRecordByPid(pid);
3820         if (appRecord == nullptr) {
3821             HILOG_ERROR("no such appRecord");
3822             return;
3823         }
3824         std::string name = appRecord->GetBundleName();
3825         if (bundleName == name) {
3826             HILOG_INFO("waitSaveTask timeout %{public}s,pid == %{public}d is going to exit due to AppRecovery.",
3827                 bundleName.c_str(), pid);
3828             innerService->KillProcessByPid(pid);
3829         }
3830     };
3831     constexpr int32_t timeOut = 2000;
3832     taskHandler_->SubmitTask(waitSaveTask, timeOutName, timeOut);
3833 }
3834 
NotifyAppFault(const FaultData & faultData)3835 int32_t AppMgrServiceInner::NotifyAppFault(const FaultData &faultData)
3836 {
3837     HILOG_DEBUG("called.");
3838     int32_t callerUid = IPCSkeleton::GetCallingUid();
3839     int32_t pid = IPCSkeleton::GetCallingPid();
3840     auto appRecord = GetAppRunningRecordByPid(pid);
3841     if (appRecord == nullptr) {
3842         HILOG_ERROR("no such appRecord");
3843         return ERR_INVALID_VALUE;
3844     }
3845     std::string bundleName = appRecord->GetBundleName();
3846 
3847     if (faultData.faultType == FaultDataType::APP_FREEZE) {
3848         if (faultData.timeoutMarkers != "") {
3849             if (!taskHandler_->CancelTask(faultData.timeoutMarkers)) {
3850                 return ERR_OK;
3851             }
3852         }
3853 
3854         if (faultData.waitSaveState) {
3855             AppRecoveryNotifyApp(pid, bundleName, FaultDataType::APP_FREEZE, "recoveryTimeout");
3856         }
3857     }
3858 
3859     auto notifyAppTask = [appRecord, pid, callerUid, bundleName, faultData, innerService = shared_from_this()]() {
3860         if (faultData.faultType == FaultDataType::APP_FREEZE) {
3861             AppfreezeManager::AppInfo info = {
3862                 .pid = pid,
3863                 .uid = callerUid,
3864                 .bundleName = bundleName,
3865                 .processName = bundleName,
3866             };
3867             auto appfreezeManager = AppExecFwk::AppfreezeManager::GetInstance();
3868             if (!appfreezeManager->IsHandleAppfreeze(bundleName)) {
3869                 return;
3870             }
3871             appfreezeManager->AppfreezeHandle(faultData, info);
3872         }
3873 
3874         HILOG_WARN("FaultData is: name: %{public}s, faultType: %{public}d, uid: %{public}d, pid: %{public}d,"
3875             "bundleName: %{public}s, faultData.forceExit==%{public}d, faultData.waitSaveState==%{public}d",
3876             faultData.errorObject.name.c_str(), faultData.faultType,
3877             callerUid, pid, bundleName.c_str(), faultData.forceExit, faultData.waitSaveState);
3878 
3879         if (faultData.forceExit && !faultData.waitSaveState && appRecord->IsKeepAliveApp()) {
3880             HILOG_INFO("FaultData %{public}s,pid == %{public}d is going to exit due to %{public}s.",
3881                 bundleName.c_str(), pid, innerService->FaultTypeToString(faultData.faultType).c_str());
3882             innerService->KillProcessByPid(pid);
3883             return;
3884         }
3885     };
3886 
3887     taskHandler_->SubmitTask(notifyAppTask, "notifyAppFaultTask");
3888     return ERR_OK;
3889 }
3890 
TimeoutNotifyApp(int32_t pid,int32_t uid,const std::string & bundleName,const FaultData & faultData)3891 void AppMgrServiceInner::TimeoutNotifyApp(int32_t pid, int32_t uid,
3892     const std::string& bundleName, const FaultData &faultData)
3893 {
3894     if (faultData.faultType == FaultDataType::APP_FREEZE) {
3895         AppfreezeManager::AppInfo info = {
3896             .pid = pid,
3897             .uid = uid,
3898             .bundleName = bundleName,
3899             .processName = bundleName,
3900         };
3901         AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
3902     }
3903     HILOG_WARN("FaultData timeout NotifyApp %{public}s is going to exit due to %{public}s.",
3904         bundleName.c_str(), FaultTypeToString(faultData.faultType).c_str());
3905     KillProcessByPid(pid);
3906 }
3907 
NotifyAppFaultBySA(const AppFaultDataBySA & faultData)3908 int32_t AppMgrServiceInner::NotifyAppFaultBySA(const AppFaultDataBySA &faultData)
3909 {
3910     HILOG_DEBUG("called");
3911     std::string callerBundleName;
3912     if (auto bundleMgr = remoteClientManager_->GetBundleManager(); bundleMgr != nullptr) {
3913         IN_PROCESS_CALL(bundleMgr->GetNameForUid(IPCSkeleton::GetCallingUid(), callerBundleName));
3914     }
3915 #ifdef ABILITY_FAULT_AND_EXIT_TEST
3916     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) ||
3917         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
3918 #else
3919     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) ||
3920         callerBundleName == SCENE_BOARD_BUNDLE_NAME) {
3921 #endif
3922         int32_t pid = faultData.pid;
3923         auto appRecord = GetAppRunningRecordByPid(pid);
3924         if (appRecord == nullptr) {
3925             HILOG_ERROR("no such appRecord");
3926             return ERR_INVALID_VALUE;
3927         }
3928 
3929         int64_t time = SystemTimeMillisecond();
3930         FaultData transformedFaultData = ConvertDataTypes(faultData);
3931         int32_t uid = appRecord->GetUid();
3932         std::string bundleName = appRecord->GetBundleName();
3933 
3934         if (faultData.errorObject.name == "appRecovery") {
3935             AppRecoveryNotifyApp(pid, bundleName, faultData.faultType, "appRecovery");
3936             return ERR_OK;
3937         }
3938 
3939         if (transformedFaultData.timeoutMarkers.empty()) {
3940             transformedFaultData.timeoutMarkers = "notifyFault" + std::to_string(pid) + "-" + std::to_string(time);
3941         }
3942         const int64_t timeout = 3000;
3943         if (faultData.faultType == FaultDataType::APP_FREEZE) {
3944             if (!AppExecFwk::AppfreezeManager::GetInstance()->IsHandleAppfreeze(bundleName)) {
3945                 return ERR_OK;
3946             }
3947             auto timeoutNotifyApp = std::bind(&AppMgrServiceInner::TimeoutNotifyApp, this,
3948                 pid, uid, bundleName, transformedFaultData);
3949             taskHandler_->SubmitTask(timeoutNotifyApp, transformedFaultData.timeoutMarkers, timeout);
3950         }
3951         appRecord->NotifyAppFault(transformedFaultData);
3952         HILOG_WARN("FaultDataBySA is: name: %{public}s, faultType: %{public}s, uid: %{public}d,"
3953             "pid: %{public}d, bundleName: %{public}s",
3954             faultData.errorObject.name.c_str(), FaultTypeToString(faultData.faultType).c_str(),
3955             uid, pid, bundleName.c_str());
3956     } else {
3957         HILOG_DEBUG("this is not called by SA.");
3958         return AAFwk::CHECK_PERMISSION_FAILED;
3959     }
3960     return ERR_OK;
3961 }
3962 
3963 FaultData AppMgrServiceInner::ConvertDataTypes(const AppFaultDataBySA &faultData)
3964 {
3965     FaultData newfaultData;
3966     newfaultData.faultType = faultData.faultType;
3967     newfaultData.errorObject = faultData.errorObject;
3968     newfaultData.timeoutMarkers = faultData.timeoutMarkers;
3969     newfaultData.waitSaveState = faultData.waitSaveState;
3970     newfaultData.notifyApp = faultData.notifyApp;
3971     newfaultData.forceExit = faultData.forceExit;
3972     return newfaultData;
3973 }
3974 
3975 std::string AppMgrServiceInner::FaultTypeToString(AppExecFwk::FaultDataType type)
3976 {
3977     std::string typeStr = "UNKNOWN";
3978     switch (type) {
3979         case AppExecFwk::FaultDataType::CPP_CRASH:
3980             typeStr = "CPP_CRASH";
3981             break;
3982         case AppExecFwk::FaultDataType::JS_ERROR:
3983             typeStr = "JS_ERROR";
3984             break;
3985         case AppExecFwk::FaultDataType::APP_FREEZE:
3986             typeStr = "APP_FREEZE";
3987             break;
3988         case AppExecFwk::FaultDataType::PERFORMANCE_CONTROL:
3989             typeStr = "PERFORMANCE_CONTROL";
3990             break;
3991         case AppExecFwk::FaultDataType::RESOURCE_CONTROL:
3992             typeStr = "RESOURCE_CONTROL";
3993             break;
3994         default:
3995             break;
3996     }
3997     return typeStr;
3998 }
3999 
4000 bool AppMgrServiceInner::IsSharedBundleRunning(const std::string &bundleName, uint32_t versionCode)
4001 {
4002     if (!CheckGetRunningInfoPermission()) {
4003         return false;
4004     }
4005     for (const auto &it : runningSharedBundleList_) {
4006         for (const auto &item : it.second) {
4007             if (item.bundleName == bundleName && item.versionCode == versionCode) {
4008                 return true;
4009             }
4010         }
4011     }
4012     return false;
4013 }
4014 
4015 int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &want) const
4016 {
4017     auto&& bundleMgr = remoteClientManager_->GetBundleManager();
4018     if (bundleMgr == nullptr) {
4019         HILOG_ERROR("GetBundleManager fail");
4020         return ERR_INVALID_OPERATION;
4021     }
4022 
4023     if (appRunningManager_ == nullptr) {
4024         HILOG_ERROR("appRunningManager_ is nullptr");
4025         return ERR_INVALID_OPERATION;
4026     }
4027     HILOG_INFO("debuggablePipe bundleName:%{public}s", want.GetElement().GetBundleName().c_str());
4028     HILOG_INFO("debuggablePipe moduleName:%{public}s", want.GetElement().GetModuleName().c_str());
4029     HILOG_INFO("debuggablePipe abilityName:%{public}s", want.GetElement().GetAbilityName().c_str());
4030 
4031     auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION |
4032         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION |
4033         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA);
4034     AbilityInfo abilityInfo;
4035     auto userId = GetCurrentAccountId();
4036     IN_PROCESS_CALL_WITHOUT_RET(bundleMgr->QueryAbilityInfo(want, abilityInfoFlag, userId, abilityInfo));
4037 
4038     BundleInfo bundleInfo;
4039     HapModuleInfo hapModuleInfo;
4040     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
4041     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, 0)) {
4042         HILOG_ERROR("GetBundleAndHapInfo failed");
4043         return ERR_INVALID_OPERATION;
4044     }
4045 
4046     std::string processName;
4047     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
4048     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, 0, processName);
4049 
4050     auto&& appRecord =
4051         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
4052     if (appRecord == nullptr) {
4053         HILOG_ERROR("The appRecord not found.");
4054         return ERR_INVALID_OPERATION;
4055     }
4056 
4057     bool isSanboxApp = want.GetBoolParam(ENTER_SANBOX, false);
4058     auto&& cmd = want.GetStringParam(PERF_CMD);
4059     if (cmd.size() == 0) {
4060         cmd = want.GetStringParam(DEBUG_CMD);
4061         return StartPerfProcess(appRecord, "", cmd, isSanboxApp);
4062     } else {
4063         return StartPerfProcess(appRecord, cmd, "", isSanboxApp);
4064     }
4065 }
4066 
4067 int32_t AppMgrServiceInner::GetCurrentAccountId() const
4068 {
4069     std::vector<int32_t> osActiveAccountIds;
4070     ErrCode ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4071         QueryActiveOsAccountIds(osActiveAccountIds);
4072     if (ret != ERR_OK) {
4073         HILOG_ERROR("QueryActiveOsAccountIds failed.");
4074         return DEFAULT_USER_ID;
4075     }
4076     if (osActiveAccountIds.empty()) {
4077         HILOG_ERROR("%{public}s, QueryActiveOsAccountIds is empty, no accounts.", __func__);
4078         return DEFAULT_USER_ID;
4079     }
4080 
4081     return osActiveAccountIds.front();
4082 }
4083 
4084 void AppMgrServiceInner::SetRunningSharedBundleList(const std::string &bundleName,
4085     const std::vector<BaseSharedBundleInfo> baseSharedBundleInfoList)
4086 {
4087     runningSharedBundleList_.try_emplace(bundleName, baseSharedBundleInfoList);
4088 }
4089 
4090 void AppMgrServiceInner::RemoveRunningSharedBundleList(const std::string &bundleName)
4091 {
4092     auto iterator = runningSharedBundleList_.find(bundleName);
4093     if (iterator == runningSharedBundleList_.end()) {
4094         return;
4095     }
4096     runningSharedBundleList_.erase(iterator);
4097 }
4098 
4099 void AppMgrServiceInner::SetCurrentUserId(const int32_t userId)
4100 {
4101     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
4102         return;
4103     }
4104     HILOG_DEBUG("set current userId: %{public}d", userId);
4105     currentUserId_ = userId;
4106 }
4107 
4108 int32_t AppMgrServiceInner::GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid)
4109 {
4110     HILOG_DEBUG("Called.");
4111     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4112         HILOG_ERROR("Permission verification failed.");
4113         return ERR_PERMISSION_DENIED;
4114     }
4115     auto callerRecord = GetAppRunningRecordByPid(pid);
4116     if (callerRecord == nullptr) {
4117         HILOG_ERROR("callerRecord is nullptr, can not get callerBundleName.");
4118         return ERR_INVALID_OPERATION;
4119     }
4120     bundleName = callerRecord->GetBundleName();
4121     uid = callerRecord->GetUid();
4122     return ERR_OK;
4123 }
4124 
4125 void AppMgrServiceInner::KillRenderProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
4126     if (appRecord == nullptr) {
4127         HILOG_ERROR("appRecord is nullptr.");
4128         return;
4129     }
4130     auto renderRecordMap = appRecord->GetRenderRecordMap();
4131     if (!renderRecordMap.empty()) {
4132         for (auto iter : renderRecordMap) {
4133             auto renderRecord = iter.second;
4134             if (renderRecord && renderRecord->GetPid() > 0) {
4135                 HILOG_DEBUG("Kill render process when host died.");
4136                 KillProcessByPid(renderRecord->GetPid());
4137                 {
4138                     std::lock_guard lock(renderUidSetLock_);
4139                     renderUidSet_.erase(renderRecord->GetUid());
4140                 }
4141                 DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
4142             }
4143         }
4144     }
4145 }
4146 
4147 int32_t AppMgrServiceInner::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize)
4148 {
4149     CHECK_CALLER_IS_SYSTEM_APP;
4150     uint64_t memSize = OHOS::MemInfo::GetPssByPid(pid);
4151     memorySize = static_cast<int32_t>(memSize);
4152     return ERR_OK;
4153 }
4154 
4155 int32_t AppMgrServiceInner::GetRunningProcessInformation(
4156     const std::string &bundleName, int32_t userId, std::vector<RunningProcessInfo> &info)
4157 {
4158     CHECK_CALLER_IS_SYSTEM_APP;
4159     if (!appRunningManager_) {
4160         HILOG_ERROR("appRunningManager nullptr!");
4161         return ERR_NO_INIT;
4162     }
4163 
4164     if (remoteClientManager_ == nullptr) {
4165         HILOG_ERROR("remoteClientManager_ nullptr!");
4166         return ERR_NO_INIT;
4167     }
4168     auto bundleMgr = remoteClientManager_->GetBundleManager();
4169     if (bundleMgr == nullptr) {
4170         HILOG_ERROR("bundleMgr nullptr!");
4171         return ERR_NO_INIT;
4172     }
4173     HILOG_INFO("userid value is %{public}d", userId);
4174     int uid = IN_PROCESS_CALL(bundleMgr->GetUidByBundleName(bundleName, userId));
4175     HILOG_INFO("uid value is %{public}d", uid);
4176     const auto &appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
4177     for (const auto &item : appRunningRecordMap) {
4178         const auto &appRecord = item.second;
4179         if (appRecord == nullptr) {
4180             continue;
4181         }
4182         auto appInfoList = appRecord->GetAppInfoList();
4183         for (const auto &appInfo : appInfoList) {
4184             if (appInfo == nullptr) {
4185                 continue;
4186             }
4187             if (appInfo->bundleName == bundleName && appInfo->uid == uid) {
4188                 GetRunningProcesses(appRecord, info);
4189                 break;
4190             }
4191         }
4192     }
4193     return ERR_OK;
4194 }
4195 }  // namespace AppExecFwk
4196 }  // namespace OHOS
4197