• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2022 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 <csignal>
19 #include <securec.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 
23 #include "accesstoken_kit.h"
24 #include "app_mem_info.h"
25 #include "app_mgr_service.h"
26 #include "app_process_data.h"
27 #include "app_state_observer_manager.h"
28 #include "application_state_observer_stub.h"
29 #include "bundle_constants.h"
30 #include "common_event.h"
31 #include "common_event_manager.h"
32 #include "common_event_support.h"
33 #include "datetime_ex.h"
34 #include "event_report.h"
35 #include "hilog_wrapper.h"
36 #include "hisysevent.h"
37 #include "hitrace_meter.h"
38 #include "in_process_call_wrapper.h"
39 #include "ipc_skeleton.h"
40 #include "iremote_object.h"
41 #include "iservice_registry.h"
42 #include "itest_observer.h"
43 #ifdef SUPPORT_GRAPHICS
44 #include "locale_config.h"
45 #endif
46 #include "parameter.h"
47 #include "parameters.h"
48 #include "perf_profile.h"
49 #include "permission_constants.h"
50 #include "permission_verification.h"
51 #include "system_ability_definition.h"
52 #include "uri_permission_manager_client.h"
53 
54 namespace OHOS {
55 namespace AppExecFwk {
56 using namespace OHOS::Rosen;
57 using namespace OHOS::Security;
58 
59 namespace {
60 // NANOSECONDS mean 10^9 nano second
61 constexpr int64_t NANOSECONDS = 1000000000;
62 // MICROSECONDS mean 10^6 milli second
63 constexpr int64_t MICROSECONDS = 1000000;
64 // Kill process timeout setting
65 constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000;
66 // Kill process delay time setting
67 constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200;
68 // delay register focus listener to wms
69 constexpr int REGISTER_FOCUS_DELAY = 5000;
70 const std::string CLASS_NAME = "ohos.app.MainThread";
71 const std::string FUNC_NAME = "main";
72 const std::string SO_PATH = "system/lib64/libmapleappkit.z.so";
73 const std::string RENDER_PARAM = "invalidparam";
74 const std::string COLD_START = "coldStart";
75 const std::string DLP_PARAMS_INDEX = "ohos.dlp.params.index";
76 const std::string PERMISSION_INTERNET = "ohos.permission.INTERNET";
77 const std::string PERMISSION_ACCESS_BUNDLE_DIR = "ohos.permission.ACCESS_BUNDLE_DIR";
78 const std::string DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
79 const int32_t SIGNAL_KILL = 9;
80 constexpr int32_t USER_SCALE = 200000;
81 #define ENUM_TO_STRING(s) #s
82 #define APP_ACCESS_BUNDLE_DIR 0x20
83 
84 constexpr int32_t BASE_USER_RANGE = 200000;
85 
86 constexpr int32_t MAX_RESTART_COUNT = 3;
87 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
88 
89 constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01);
90 constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100; // error code for already exist render.
91 const std::string EVENT_NAME_LIFECYCLE_TIMEOUT = "APP_LIFECYCLE_TIMEOUT";
92 constexpr char EVENT_KEY_UID[] = "UID";
93 constexpr char EVENT_KEY_PID[] = "PID";
94 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
95 constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME";
96 constexpr char EVENT_KEY_MESSAGE[] = "MSG";
97 
98 // Msg length is less than 48 characters
99 const std::string EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!";
100 const std::string EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!";
101 const std::string EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT = "Add Ability Stage TimeOut!";
102 const std::string EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!";
103 const std::string EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = "Start Process Specified Ability TimeOut!";
104 const std::string EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!";
105 
106 const std::string SYSTEM_BASIC = "system_basic";
107 const std::string SYSTEM_CORE = "system_core";
108 const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
109 
110 constexpr int32_t ROOT_UID = 0;
111 constexpr int32_t FOUNDATION_UID = 5523;
112 
GetUserIdByUid(int32_t uid)113 int32_t GetUserIdByUid(int32_t uid)
114 {
115     return uid / BASE_USER_RANGE;
116 }
117 }  // namespace
118 
119 using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED;
120 using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
121 
AppMgrServiceInner()122 AppMgrServiceInner::AppMgrServiceInner()
123     : appProcessManager_(std::make_shared<AppProcessManager>()),
124       remoteClientManager_(std::make_shared<RemoteClientManager>()),
125       appRunningManager_(std::make_shared<AppRunningManager>()),
126       configuration_(std::make_shared<Configuration>())
127 {}
128 
Init()129 void AppMgrServiceInner::Init()
130 {
131     InitGlobalConfiguration();
132     AddWatchParameter();
133     DelayedSingleton<AppStateObserverManager>::GetInstance()->Init();
134     InitFocusListener();
135 }
136 
~AppMgrServiceInner()137 AppMgrServiceInner::~AppMgrServiceInner()
138 {}
139 
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)140 void AppMgrServiceInner::LoadAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
141     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
142     const std::shared_ptr<AAFwk::Want> &want)
143 {
144     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
145     if (!CheckLoadAbilityConditions(token, abilityInfo, appInfo)) {
146         HILOG_ERROR("CheckLoadAbilityConditions failed");
147         return;
148     }
149     HILOG_INFO("AppMgrService start loading ability, name is %{public}s.", abilityInfo->name.c_str());
150 
151     if (!appRunningManager_) {
152         HILOG_ERROR("appRunningManager_ is nullptr");
153         return;
154     }
155 
156     BundleInfo bundleInfo;
157     HapModuleInfo hapModuleInfo;
158     int32_t appIndex = (want == nullptr) ? 0 : want->GetIntParam(DLP_PARAMS_INDEX, 0);
159     if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
160         HILOG_ERROR("GetBundleAndHapInfo failed");
161         return;
162     }
163 
164     std::string processName;
165     MakeProcessName(abilityInfo, appInfo, hapModuleInfo, appIndex, processName);
166 
167     auto appRecord =
168         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
169     if (!appRecord) {
170         appRecord = CreateAppRunningRecord(token, preToken, appInfo, abilityInfo,
171             processName, bundleInfo, hapModuleInfo, want);
172         if (!appRecord) {
173             HILOG_ERROR("CreateAppRunningRecord failed, appRecord is nullptr");
174             return;
175         }
176         uint32_t startFlags = (want == nullptr) ? 0 : BuildStartFlags(*want, *abilityInfo);
177         int32_t bundleIndex = (want == nullptr) ? 0 : want->GetIntParam(DLP_PARAMS_INDEX, 0);
178         StartProcess(abilityInfo->applicationName, processName, startFlags, appRecord,
179             appInfo->uid, appInfo->bundleName, bundleIndex);
180     } else {
181         int32_t requestProcCode = (want == nullptr) ? 0 : want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0);
182         if (requestProcCode != 0 && appRecord->GetRequestProcCode() == 0) {
183             appRecord->SetRequestProcCode(requestProcCode);
184             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessReused(appRecord);
185         }
186         StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want);
187     }
188     PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
189     PerfProfile::GetInstance().Dump();
190     PerfProfile::GetInstance().Reset();
191 }
192 
CheckLoadAbilityConditions(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo)193 bool AppMgrServiceInner::CheckLoadAbilityConditions(const sptr<IRemoteObject> &token,
194     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo)
195 {
196     if (!token || !abilityInfo || !appInfo) {
197         HILOG_ERROR("param error");
198         return false;
199     }
200     if (abilityInfo->name.empty() || appInfo->name.empty()) {
201         HILOG_ERROR("error abilityInfo or appInfo");
202         return false;
203     }
204     if (abilityInfo->applicationName != appInfo->name) {
205         HILOG_ERROR("abilityInfo and appInfo have different appName, don't load for it");
206         return false;
207     }
208 
209     return true;
210 }
211 
MakeProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,int32_t appIndex,std::string & processName)212 void AppMgrServiceInner::MakeProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
213     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, int32_t appIndex,
214     std::string &processName)
215 {
216     if (!abilityInfo || !appInfo) {
217         HILOG_ERROR("param error");
218         return;
219     }
220     if (!abilityInfo->process.empty()) {
221         processName = abilityInfo->process;
222         return;
223     }
224     MakeProcessName(appInfo, hapModuleInfo, processName);
225     if (appIndex != 0) {
226         processName += std::to_string(appIndex);
227     }
228 }
229 
MakeProcessName(const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,std::string & processName)230 void AppMgrServiceInner::MakeProcessName(
231     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, std::string &processName)
232 {
233     if (!appInfo) {
234         return;
235     }
236     // check after abilityInfo, because abilityInfo contains extension process.
237     if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()) {
238         processName = hapModuleInfo.process;
239         HILOG_INFO("Stage mode, Make processName:%{public}s", processName.c_str());
240         return;
241     }
242     if (!appInfo->process.empty()) {
243         processName = appInfo->process;
244         return;
245     }
246     processName = appInfo->bundleName;
247 }
248 
GetBundleAndHapInfo(const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo,int32_t appIndex)249 bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo,
250     const std::shared_ptr<ApplicationInfo> &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo,
251     int32_t appIndex)
252 {
253     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
254     if (bundleMgr_ == nullptr) {
255         HILOG_ERROR("GetBundleManager fail");
256         return false;
257     }
258 
259     auto userId = GetUserIdByUid(appInfo->uid);
260     HILOG_INFO("GetBundleAndHapInfo come, call bms GetBundleInfo and GetHapModuleInfo, userId is %{public}d", userId);
261     bool bundleMgrResult;
262     if (appIndex == 0) {
263         bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfo(appInfo->bundleName,
264             BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
265     } else {
266         bundleMgrResult = (IN_PROCESS_CALL(bundleMgr_->GetSandboxBundleInfo(appInfo->bundleName,
267             appIndex, userId, bundleInfo)) == 0);
268     }
269 
270     if (!bundleMgrResult) {
271         HILOG_ERROR("GetBundleInfo is fail");
272         return false;
273     }
274     if (appIndex == 0) {
275         bundleMgrResult = bundleMgr_->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo);
276     } else {
277         bundleMgrResult = (bundleMgr_->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0);
278     }
279     if (!bundleMgrResult) {
280         HILOG_ERROR("GetHapModuleInfo is fail");
281         return false;
282     }
283 
284     return true;
285 }
286 
AttachApplication(const pid_t pid,const sptr<IAppScheduler> & appScheduler)287 void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &appScheduler)
288 {
289     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
290     if (pid <= 0) {
291         HILOG_ERROR("invalid pid:%{public}d", pid);
292         return;
293     }
294     if (!appScheduler) {
295         HILOG_ERROR("app client is null");
296         return;
297     }
298     HILOG_INFO("AppMgrService attach application come, pid is %{public}d.", pid);
299     auto appRecord = GetAppRunningRecordByPid(pid);
300     if (!appRecord) {
301         HILOG_ERROR("no such appRecord");
302         return;
303     }
304     appRecord->SetApplicationClient(appScheduler);
305     if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
306         LaunchApplication(appRecord);
307     }
308     appRecord->RegisterAppDeathRecipient();
309     AAFwk::EventInfo eventInfo;
310     auto applicationInfo = appRecord->GetApplicationInfo();
311     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
312     eventInfo.bundleName = applicationInfo->name;
313     eventInfo.versionName = applicationInfo->versionName;
314     eventInfo.versionCode = applicationInfo->versionCode;
315     eventInfo.processName = appRecord->GetProcessName();
316     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_ATTACH, HiSysEventType::BEHAVIOR, eventInfo);
317 }
318 
LaunchApplication(const std::shared_ptr<AppRunningRecord> & appRecord)319 void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
320 {
321     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
322     if (!appRecord) {
323         HILOG_ERROR("appRecord is null");
324         return;
325     }
326 
327     if (!configuration_) {
328         HILOG_ERROR("configuration_ is null");
329         return;
330     }
331 
332     if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
333         HILOG_ERROR("wrong app state:%{public}d", appRecord->GetState());
334         return;
335     }
336 
337     appRecord->LaunchApplication(*configuration_);
338     appRecord->SetState(ApplicationState::APP_STATE_READY);
339     int restartResidentProcCount = MAX_RESTART_COUNT;
340     appRecord->SetRestartResidentProcCount(restartResidentProcCount);
341 
342     // There is no ability when the empty resident process starts
343     // The status of all resident processes is ready
344     // There is no process of switching the foreground, waiting for his first ability to start
345     if (appRecord->IsEmptyKeepAliveApp()) {
346         appRecord->AddAbilityStage();
347         return;
348     }
349 
350     if (appRecord->IsStartSpecifiedAbility()) {
351         appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
352         return;
353     }
354     appRecord->LaunchPendingAbilities();
355     AAFwk::EventInfo eventInfo;
356     auto applicationInfo = appRecord->GetApplicationInfo();
357     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
358     eventInfo.bundleName = applicationInfo->name;
359     eventInfo.versionName = applicationInfo->versionName;
360     eventInfo.versionCode = applicationInfo->versionCode;
361     eventInfo.processName = appRecord->GetProcessName();
362     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_LAUNCH, HiSysEventType::BEHAVIOR, eventInfo);
363 }
364 
AddAbilityStageDone(const int32_t recordId)365 void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId)
366 {
367     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
368     if (!appRecord) {
369         HILOG_ERROR("get app record failed");
370         return;
371     }
372     appRecord->AddAbilityStageDone();
373 }
374 
ApplicationForegrounded(const int32_t recordId)375 void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId)
376 {
377     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
378     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
379     if (!appRecord) {
380         HILOG_ERROR("get app record failed");
381         return;
382     }
383     appRecord->PopForegroundingAbilityTokens();
384     ApplicationState appState = appRecord->GetState();
385     if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) {
386         appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND);
387         bool needNotifyApp = appRunningManager_->IsApplicationFirstForeground(*appRecord);
388         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp);
389         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
390     } else {
391         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
392             appRecord->GetName().c_str(), static_cast<ApplicationState>(appState));
393     }
394 
395     // push the foregrounded app front of RecentAppList.
396     PushAppFront(recordId);
397     HILOG_INFO("application is foregrounded");
398     AAFwk::EventInfo eventInfo;
399     auto applicationInfo = appRecord->GetApplicationInfo();
400     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
401     eventInfo.bundleName = applicationInfo->name;
402     eventInfo.versionName = applicationInfo->versionName;
403     eventInfo.versionCode = applicationInfo->versionCode;
404     eventInfo.processName = appRecord->GetProcessName();
405     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_FOREGROUND, HiSysEventType::BEHAVIOR, eventInfo);
406 }
407 
ApplicationBackgrounded(const int32_t recordId)408 void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId)
409 {
410     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
411     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
412     if (!appRecord) {
413         HILOG_ERROR("get app record failed");
414         return;
415     }
416     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
417         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
418         bool needNotifyApp = appRunningManager_->IsApplicationBackground(appRecord->GetBundleName());
419         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND, needNotifyApp);
420         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
421     } else {
422         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
423             appRecord->GetName().c_str(), static_cast<ApplicationState>(appRecord->GetState()));
424     }
425 
426     HILOG_INFO("application is backgrounded");
427     AAFwk::EventInfo eventInfo;
428     auto applicationInfo = appRecord->GetApplicationInfo();
429     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
430     eventInfo.bundleName = applicationInfo->name;
431     eventInfo.versionName = applicationInfo->versionName;
432     eventInfo.versionCode = applicationInfo->versionCode;
433     eventInfo.processName = appRecord->GetProcessName();
434     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_BACKGROUND, HiSysEventType::BEHAVIOR, eventInfo);
435 }
436 
ApplicationTerminated(const int32_t recordId)437 void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
438 {
439     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
440     if (!appRunningManager_) {
441         HILOG_ERROR("appRunningManager_ is nullptr");
442         return;
443     }
444 
445     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
446     if (!appRecord) {
447         HILOG_ERROR("get app record failed");
448         return;
449     }
450     appRecord->ApplicationTerminated();
451     // Maybe can't get in here
452     if (appRecord->IsKeepAliveApp()) {
453         return;
454     }
455     if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
456         HILOG_ERROR("current state is not background");
457         return;
458     }
459     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
460     appRecord->RemoveAppDeathRecipient();
461     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED);
462     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false);
463     appRunningManager_->RemoveAppRunningRecordById(recordId);
464     RemoveAppFromRecentListById(recordId);
465     AAFwk::EventInfo eventInfo;
466     auto applicationInfo = appRecord->GetApplicationInfo();
467     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
468     eventInfo.bundleName = applicationInfo->name;
469     eventInfo.versionName = applicationInfo->versionName;
470     eventInfo.versionCode = applicationInfo->versionCode;
471     eventInfo.processName = appRecord->GetProcessName();
472     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
473     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
474 
475     HILOG_INFO("application is terminated");
476 }
477 
UpdateApplicationInfoInstalled(const std::string & bundleName,const int uid)478 int32_t AppMgrServiceInner::UpdateApplicationInfoInstalled(const std::string &bundleName, const int uid)
479 {
480     if (!appRunningManager_) {
481         HILOG_ERROR("appRunningManager_ is nullptr");
482         return ERR_NO_INIT;
483     }
484 
485     int32_t result = VerifyProcessPermission(bundleName);
486     if (result != ERR_OK) {
487         HILOG_ERROR("Permission verification failed");
488         return result;
489     }
490 
491     if (remoteClientManager_ == nullptr) {
492         HILOG_ERROR("remoteClientManager_ fail");
493         return ERR_NO_INIT;
494     }
495 
496     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
497     if (bundleMgr_ == nullptr) {
498         HILOG_ERROR("GetBundleManager fail");
499         return ERR_NO_INIT;
500     }
501     auto userId = GetUserIdByUid(uid);
502     ApplicationInfo appInfo;
503     HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetApplicationInfo");
504     bool bundleMgrResult = bundleMgr_->GetApplicationInfo(bundleName,
505         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo);
506     if (!bundleMgrResult) {
507         HILOG_ERROR("GetApplicationInfo is fail");
508         return ERR_INVALID_OPERATION;
509     }
510 
511     HILOG_DEBUG("uid value is %{public}d", uid);
512     result = appRunningManager_->ProcessUpdateApplicationInfoInstalled(appInfo);
513     if (result != ERR_OK) {
514         HILOG_INFO("The process corresponding to the package name did not start");
515     }
516 
517     return result;
518 }
519 
KillApplication(const std::string & bundleName)520 int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName)
521 {
522     if (!appRunningManager_) {
523         HILOG_ERROR("appRunningManager_ is nullptr");
524         return ERR_NO_INIT;
525     }
526 
527     auto result = VerifyProcessPermission(bundleName);
528     if (result != ERR_OK) {
529         HILOG_ERROR("Permission verification failed.");
530         return result;
531     }
532 
533     return KillApplicationByBundleName(bundleName);
534 }
535 
KillApplicationByUid(const std::string & bundleName,const int uid)536 int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid)
537 {
538     if (!appRunningManager_) {
539         HILOG_ERROR("appRunningManager_ is nullptr");
540         return ERR_NO_INIT;
541     }
542 
543     auto result = VerifyProcessPermission(bundleName);
544     if (result != ERR_OK) {
545         HILOG_ERROR("Permission verification failed.");
546         return result;
547     }
548 
549     result = ERR_OK;
550     int64_t startTime = SystemTimeMillisecond();
551     std::list<pid_t> pids;
552     if (remoteClientManager_ == nullptr) {
553         HILOG_ERROR("remoteClientManager_ fail");
554         return ERR_NO_INIT;
555     }
556     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
557     if (bundleMgr_ == nullptr) {
558         HILOG_ERROR("GetBundleManager fail");
559         return ERR_NO_INIT;
560     }
561     HILOG_INFO("uid value is %{public}d", uid);
562     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
563         HILOG_INFO("The process corresponding to the package name did not start");
564         return result;
565     }
566     if (WaitForRemoteProcessExit(pids, startTime)) {
567         HILOG_INFO("The remote process exited successfully ");
568         return result;
569     }
570     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
571         result = KillProcessByPid(*iter);
572         if (result < 0) {
573             HILOG_ERROR("KillApplication failed for bundleName:%{public}s pid:%{public}d", bundleName.c_str(), *iter);
574             return result;
575         }
576     }
577     return result;
578 }
579 
KillApplicationSelf()580 int32_t AppMgrServiceInner::KillApplicationSelf()
581 {
582     if (!appRunningManager_) {
583         HILOG_ERROR("appRunningManager_ is nullptr");
584         return ERR_NO_INIT;
585     }
586 
587     auto callerPid = IPCSkeleton::GetCallingPid();
588     auto appRecord = GetAppRunningRecordByPid(callerPid);
589     if (!appRecord) {
590         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
591         return ERR_INVALID_VALUE;
592     }
593     auto bundleName = appRecord->GetBundleName();
594     return KillApplicationByBundleName(bundleName);
595 }
596 
KillApplicationByBundleName(const std::string & bundleName)597 int32_t AppMgrServiceInner::KillApplicationByBundleName(const std::string &bundleName)
598 {
599     int result = ERR_OK;
600     int64_t startTime = SystemTimeMillisecond();
601     std::list<pid_t> pids;
602 
603     if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids)) {
604         HILOG_ERROR("The process corresponding to the package name did not start");
605         return result;
606     }
607     if (WaitForRemoteProcessExit(pids, startTime)) {
608         HILOG_DEBUG("The remote process exited successfully ");
609         NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
610         return result;
611     }
612     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
613         result = KillProcessByPid(*iter);
614         if (result < 0) {
615             HILOG_ERROR("KillApplicationSelf is failed for bundleName:%{public}s, pid: %{public}d",
616                 bundleName.c_str(), *iter);
617             return result;
618         }
619     }
620     NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
621     return result;
622 }
623 
KillApplicationByUserId(const std::string & bundleName,const int userId)624 int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleName, const int userId)
625 {
626     if (!appRunningManager_) {
627         HILOG_ERROR("appRunningManager_ is nullptr");
628         return ERR_NO_INIT;
629     }
630 
631     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES, userId) ==
632         ERR_PERMISSION_DENIED) {
633         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
634         return ERR_PERMISSION_DENIED;
635     }
636 
637     if (remoteClientManager_ == nullptr) {
638         HILOG_ERROR("remoteClientManager_ fail");
639         return ERR_NO_INIT;
640     }
641     auto bundleMgr = remoteClientManager_->GetBundleManager();
642     if (bundleMgr == nullptr) {
643         HILOG_ERROR("GetBundleManager fail");
644         return ERR_NO_INIT;
645     }
646 
647     return KillApplicationByUserIdLocked(bundleName, userId);
648 }
649 
KillApplicationByUserIdLocked(const std::string & bundleName,const int userId)650 int32_t AppMgrServiceInner::KillApplicationByUserIdLocked(const std::string &bundleName, const int userId)
651 {
652     if (!appRunningManager_) {
653         HILOG_ERROR("appRunningManager_ is nullptr");
654         return ERR_NO_INIT;
655     }
656 
657     int result = ERR_OK;
658     int64_t startTime = SystemTimeMillisecond();
659     std::list<pid_t> pids;
660     if (remoteClientManager_ == nullptr) {
661         HILOG_ERROR("remoteClientManager_ fail");
662         return ERR_NO_INIT;
663     }
664     auto bundleMgr = remoteClientManager_->GetBundleManager();
665     if (bundleMgr == nullptr) {
666         HILOG_ERROR("GetBundleManager fail");
667         return ERR_NO_INIT;
668     }
669 
670     HILOG_INFO("userId value is %{public}d", userId);
671     int uid = IN_PROCESS_CALL(bundleMgr->GetUidByBundleName(bundleName, userId));
672     HILOG_INFO("uid value is %{public}d", uid);
673     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
674         HILOG_INFO("The process corresponding to the package name did not start");
675         return result;
676     }
677     if (WaitForRemoteProcessExit(pids, startTime)) {
678         HILOG_INFO("The remote process exited successfully ");
679         return result;
680     }
681     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
682         result = KillProcessByPid(*iter);
683         if (result < 0) {
684             HILOG_ERROR("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter);
685             return result;
686         }
687     }
688     return result;
689 }
690 
ClearUpApplicationData(const std::string & bundleName,int32_t callerUid,pid_t callerPid)691 void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid)
692 {
693     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
694     auto userId = GetUserIdByUid(callerUid);
695     HILOG_INFO("userId:%{public}d", userId);
696     ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, userId);
697 }
698 
ClearUpApplicationDataByUserId(const std::string & bundleName,int32_t callerUid,pid_t callerPid,const int userId)699 void AppMgrServiceInner::ClearUpApplicationDataByUserId(
700     const std::string &bundleName, int32_t callerUid, pid_t callerPid, const int userId)
701 {
702     if (callerPid <= 0) {
703         HILOG_ERROR("invalid callerPid:%{public}d", callerPid);
704         return;
705     }
706     if (callerUid <= 0) {
707         HILOG_ERROR("invalid callerUid:%{public}d", callerUid);
708         return;
709     }
710     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
711     if (bundleMgr_ == nullptr) {
712         HILOG_ERROR("GetBundleManager fail");
713         return;
714     }
715 
716     // request to clear user information permission.
717     auto tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, 0);
718     int32_t result = AccessToken::AccessTokenKit::ClearUserGrantedPermissionState(tokenId);
719     if (result) {
720         HILOG_ERROR("ClearUserGrantedPermissionState failed, ret:%{public}d", result);
721         return;
722     }
723     // 2.delete bundle side user data
724     if (!IN_PROCESS_CALL(bundleMgr_->CleanBundleDataFiles(bundleName, userId))) {
725         HILOG_ERROR("Delete bundle side user data is fail");
726         return;
727     }
728     // 3.kill application
729     // 4.revoke user rights
730     result = KillApplicationByUserId(bundleName, userId);
731     if (result < 0) {
732         HILOG_ERROR("Kill Application by bundle name is fail");
733         return;
734     }
735     NotifyAppStatusByCallerUid(bundleName, userId, callerUid,
736         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
737 }
738 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)739 int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
740 {
741     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
742     // check permission
743     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
744         const auto &appRecord = item.second;
745         if (isPerm) {
746             GetRunningProcesses(appRecord, info);
747         } else {
748             auto applicationInfo = appRecord->GetApplicationInfo();
749             if (!applicationInfo) {
750                 continue;
751             }
752             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
753             auto tokenId = applicationInfo->accessTokenId;
754             if (callingTokenId == tokenId) {
755                 GetRunningProcesses(appRecord, info);
756             }
757         }
758     }
759     return ERR_OK;
760 }
761 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)762 int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
763 {
764     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
765         ERR_PERMISSION_DENIED) {
766         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
767         return ERR_PERMISSION_DENIED;
768     }
769 
770     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
771         const auto &appRecord = item.second;
772         int32_t userIdTemp = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
773         if (userIdTemp == userId) {
774             GetRunningProcesses(appRecord, info);
775         }
776     }
777     return ERR_OK;
778 }
779 
GetProcessRunningInformation(RunningProcessInfo & info)780 int32_t AppMgrServiceInner::GetProcessRunningInformation(RunningProcessInfo &info)
781 {
782     if (!appRunningManager_) {
783         HILOG_ERROR("appRunningManager_ is nullptr");
784         return ERR_NO_INIT;
785     }
786     auto callerPid = IPCSkeleton::GetCallingPid();
787     auto appRecord = GetAppRunningRecordByPid(callerPid);
788     if (!appRecord) {
789         HILOG_ERROR("no such appRecord, callerPid:%{public}d", callerPid);
790         return ERR_INVALID_VALUE;
791     }
792     GetRunningProcess(appRecord, info);
793     return ERR_OK;
794 }
795 
NotifyMemoryLevel(int32_t level)796 int32_t AppMgrServiceInner::NotifyMemoryLevel(int32_t level)
797 {
798     HILOG_INFO("AppMgrServiceInner start");
799 
800     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
801     auto isGatewayCall = AAFwk::PermissionVerification::GetInstance()->IsGatewayCall();
802     if (!isSaCall && !isGatewayCall) {
803         HILOG_ERROR("callerToken not SA %{public}s", __func__);
804         return ERR_INVALID_VALUE;
805     }
806     if (!(level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_MODERATE ||
807         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_CRITICAL ||
808         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_LOW)) {
809         HILOG_ERROR("Level value error!");
810         return ERR_INVALID_VALUE;
811     }
812     if (!appRunningManager_) {
813         HILOG_ERROR("appRunningManager nullptr!");
814         return ERR_INVALID_VALUE;
815     }
816 
817     return appRunningManager_->NotifyMemoryLevel(level);
818 }
819 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)820 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
821     std::vector<RunningProcessInfo> &info)
822 {
823     RunningProcessInfo runningProcessInfo;
824     GetRunningProcess(appRecord, runningProcessInfo);
825     info.emplace_back(runningProcessInfo);
826 }
827 
GetRunningProcess(const std::shared_ptr<AppRunningRecord> & appRecord,RunningProcessInfo & info)828 void AppMgrServiceInner::GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
829     RunningProcessInfo &info)
830 {
831     info.processName_ = appRecord->GetProcessName();
832     info.pid_ = appRecord->GetPriorityObject()->GetPid();
833     info.uid_ = appRecord->GetUid();
834     info.state_ = static_cast<AppProcessState>(appRecord->GetState());
835     info.isContinuousTask = appRecord->IsContinuousTask();
836     info.isKeepAlive = appRecord->IsKeepAliveApp();
837     info.isFocused = appRecord->GetFocusFlag();
838     info.startTimeMillis_ = appRecord->GetAppStartTime();
839     appRecord->GetBundleNames(info.bundleNames);
840 }
841 
KillProcessByPid(const pid_t pid) const842 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid) const
843 {
844     int32_t ret = -1;
845     if (pid > 0) {
846         HILOG_INFO("kill pid %{public}d", pid);
847         ret = kill(pid, SIGNAL_KILL);
848     }
849     AAFwk::EventInfo eventInfo;
850     auto appRecord = GetAppRunningRecordByPid(pid);
851     if (!appRecord) {
852         return ret;
853     }
854     auto applicationInfo = appRecord->GetApplicationInfo();
855     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
856     eventInfo.bundleName = applicationInfo->name;
857     eventInfo.versionName = applicationInfo->versionName;
858     eventInfo.versionCode = applicationInfo->versionCode;
859     eventInfo.processName = appRecord->GetProcessName();
860     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
861     return ret;
862 }
863 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)864 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
865 {
866     int64_t delayTime = SystemTimeMillisecond() - startTime;
867     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
868         if (CheckAllProcessExist(pids)) {
869             return true;
870         }
871         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
872         delayTime = SystemTimeMillisecond() - startTime;
873     }
874     return false;
875 }
876 
GetAllPids(std::list<pid_t> & pids)877 bool AppMgrServiceInner::GetAllPids(std::list<pid_t> &pids)
878 {
879     for (const auto &appTaskInfo : appProcessManager_->GetRecentAppList()) {
880         if (appTaskInfo) {
881             auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
882             if (appRecord) {
883                 pids.push_back(appTaskInfo->GetPid());
884                 appRecord->ScheduleProcessSecurityExit();
885             }
886         }
887     }
888     return (pids.empty() ? false : true);
889 }
890 
ProcessExist(pid_t & pid)891 bool AppMgrServiceInner::ProcessExist(pid_t &pid)
892 {
893     char pid_path[128] = {0};
894     struct stat stat_buf;
895     if (!pid) {
896         return false;
897     }
898     if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) {
899         return false;
900     }
901     if (stat(pid_path, &stat_buf) == 0) {
902         return true;
903     }
904     return false;
905 }
906 
CheckAllProcessExist(std::list<pid_t> & pids)907 bool AppMgrServiceInner::CheckAllProcessExist(std::list<pid_t> &pids)
908 {
909     for (auto iter = pids.begin(); iter != pids.end();) {
910         if (!ProcessExist(*iter)) {
911             iter = pids.erase(iter);
912         } else {
913             iter++;
914         }
915     }
916     if (pids.empty()) {
917         return true;
918     }
919     return false;
920 }
921 
SystemTimeMillisecond()922 int64_t AppMgrServiceInner::SystemTimeMillisecond()
923 {
924     struct timespec t;
925     t.tv_sec = 0;
926     t.tv_nsec = 0;
927     clock_gettime(CLOCK_MONOTONIC, &t);
928     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
929 }
930 
GetAppRunningRecordByPid(const pid_t pid) const931 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
932 {
933     if (!appRunningManager_) {
934         HILOG_ERROR("appRunningManager nullptr!");
935         return nullptr;
936     }
937     return appRunningManager_->GetAppRunningRecordByPid(pid);
938 }
939 
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)940 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(const sptr<IRemoteObject> &token,
941     const sptr<IRemoteObject> &preToken, const std::shared_ptr<ApplicationInfo> &appInfo,
942     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
943     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
944 {
945     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
946     if (!appRunningManager_) {
947         HILOG_ERROR("appRunningManager nullptr!");
948         return nullptr;
949     }
950     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
951     if (!appRecord) {
952         HILOG_ERROR("get app record failed");
953         return nullptr;
954     }
955 
956     bool isKeepAlive = bundleInfo.isKeepAlive && bundleInfo.singleton;
957     appRecord->SetKeepAliveAppState(isKeepAlive, false);
958     appRecord->SetEventHandler(eventHandler_);
959     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
960     if (want) {
961         appRecord->SetDebugApp(want->GetBoolParam("debugApp", false));
962         if (want->GetBoolParam(COLD_START, false)) {
963             appRecord->SetDebugApp(true);
964         }
965         appRecord->SetAppIndex(want->GetIntParam(DLP_PARAMS_INDEX, 0));
966         appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
967         appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0));
968     }
969 
970     if (preToken) {
971         auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
972         if (abilityRecord) {
973             abilityRecord->SetPreToken(preToken);
974         }
975     }
976 
977     return appRecord;
978 }
979 
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag)980 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag)
981 {
982     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
983     HILOG_DEBUG("Terminate ability come.");
984     if (!token) {
985         HILOG_ERROR("AppMgrServiceInner::TerminateAbility token is null!");
986         return;
987     }
988     auto appRecord = GetAppRunningRecordByAbilityToken(token);
989     if (!appRecord) {
990         HILOG_ERROR("AppMgrServiceInner::TerminateAbility app is not exist!");
991         return;
992     }
993 
994     if (appRunningManager_) {
995         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner = shared_from_this();
996         appRunningManager_->TerminateAbility(token, clearMissionFlag, appMgrServiceInner);
997     }
998 }
999 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)1000 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
1001 {
1002     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1003     HILOG_INFO("AppMgrService start to update the ability to state %{public}d.", static_cast<int32_t>(state));
1004     if (!token) {
1005         HILOG_ERROR("token is null!");
1006         return;
1007     }
1008 
1009     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1010     if (!appRecord) {
1011         HILOG_ERROR("app is not exist!");
1012         return;
1013     }
1014     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1015     if (!abilityRecord) {
1016         HILOG_ERROR("can not find ability record!");
1017         return;
1018     }
1019     if (state == abilityRecord->GetState()) {
1020         HILOG_ERROR("current state is already, no need update!");
1021         return;
1022     }
1023     if (abilityRecord->GetAbilityInfo() == nullptr) {
1024         HILOG_ERROR("ability info nullptr!");
1025         return;
1026     }
1027     auto type = abilityRecord->GetAbilityInfo()->type;
1028     if (type == AppExecFwk::AbilityType::SERVICE &&
1029         (state == AbilityState::ABILITY_STATE_CREATE ||
1030         state == AbilityState::ABILITY_STATE_TERMINATED ||
1031         state == AbilityState::ABILITY_STATE_CONNECTED ||
1032         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
1033         HILOG_INFO("StateChangedNotifyObserver service type, state:%{public}d", static_cast<int32_t>(state));
1034         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true);
1035         return;
1036     }
1037     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
1038         HILOG_ERROR("state is not foreground or background!");
1039         return;
1040     }
1041 
1042     appRecord->UpdateAbilityState(token, state);
1043 }
1044 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)1045 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
1046 {
1047     if (!token) {
1048         HILOG_ERROR("token is null!");
1049         return;
1050     }
1051     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1052     if (!appRecord) {
1053         HILOG_ERROR("app is not exist!");
1054         return;
1055     }
1056     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1057     if (!abilityRecord) {
1058         HILOG_ERROR("can not find ability record!");
1059         return;
1060     }
1061     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false);
1062 }
1063 
OnStop()1064 void AppMgrServiceInner::OnStop()
1065 {
1066     if (!appRunningManager_) {
1067         HILOG_ERROR("appRunningManager nullptr!");
1068         return;
1069     }
1070 
1071     appRunningManager_->ClearAppRunningRecordMap();
1072     CloseAppSpawnConnection();
1073 }
1074 
OpenAppSpawnConnection()1075 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
1076 {
1077     if (remoteClientManager_ == nullptr) {
1078         HILOG_ERROR("remoteClientManager_ is null");
1079         return ERR_INVALID_VALUE;
1080     }
1081 
1082     if (remoteClientManager_->GetSpawnClient()) {
1083         return remoteClientManager_->GetSpawnClient()->OpenConnection();
1084     }
1085     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
1086 }
1087 
CloseAppSpawnConnection() const1088 void AppMgrServiceInner::CloseAppSpawnConnection() const
1089 {
1090     if (remoteClientManager_ == nullptr) {
1091         HILOG_ERROR("remoteClientManager_ is null");
1092         return;
1093     }
1094 
1095     if (remoteClientManager_->GetSpawnClient()) {
1096         remoteClientManager_->GetSpawnClient()->CloseConnection();
1097     }
1098 }
1099 
QueryAppSpawnConnectionState() const1100 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
1101 {
1102     if (remoteClientManager_ == nullptr) {
1103         HILOG_ERROR("remoteClientManager_ is null");
1104         return SpawnConnectionState::STATE_NOT_CONNECT;
1105     }
1106 
1107     if (remoteClientManager_->GetSpawnClient()) {
1108         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
1109     }
1110     return SpawnConnectionState::STATE_NOT_CONNECT;
1111 }
1112 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)1113 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
1114 {
1115     if (remoteClientManager_ == nullptr) {
1116         HILOG_ERROR("remoteClientManager_ is null");
1117         return;
1118     }
1119 
1120     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
1121 }
1122 
SetBundleManager(sptr<IBundleMgr> bundleManager)1123 void AppMgrServiceInner::SetBundleManager(sptr<IBundleMgr> bundleManager)
1124 {
1125     if (remoteClientManager_ == nullptr) {
1126         HILOG_ERROR("remoteClientManager_ is null");
1127         return;
1128     }
1129 
1130     remoteClientManager_->SetBundleManager(bundleManager);
1131 }
1132 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)1133 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
1134 {
1135     pid_t callingPid = IPCSkeleton::GetCallingPid();
1136     pid_t pid = getpid();
1137     if (callingPid != pid) {
1138         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
1139         return;
1140     }
1141     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1142     if (callback != nullptr) {
1143         appStateCallbacks_.push_back(callback);
1144     }
1145 }
1146 
AbilityBehaviorAnalysis(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const int32_t visibility,const int32_t perceptibility,const int32_t connectionState)1147 void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1148     const int32_t visibility,       // 0:false,1:true
1149     const int32_t perceptibility,   // 0:false,1:true
1150     const int32_t connectionState)  // 0:false,1:true
1151 {
1152     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1153     if (!token) {
1154         HILOG_ERROR("token is null");
1155         return;
1156     }
1157     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1158     if (!appRecord) {
1159         HILOG_ERROR("app record is not exist for ability token");
1160         return;
1161     }
1162     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1163     if (!abilityRecord) {
1164         HILOG_ERROR("ability record is not exist for ability previous token");
1165         return;
1166     }
1167     if (preToken) {
1168         abilityRecord->SetPreToken(preToken);
1169     }
1170     abilityRecord->SetVisibility(visibility);
1171     abilityRecord->SetPerceptibility(perceptibility);
1172     abilityRecord->SetConnectionState(connectionState);
1173 }
1174 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)1175 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
1176 {
1177     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1178     if (!token) {
1179         HILOG_ERROR("token is null");
1180         return;
1181     }
1182     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1183     if (!appRecord) {
1184         HILOG_ERROR("app record is not exist for ability token");
1185         return;
1186     }
1187 
1188     // before exec ScheduleProcessSecurityExit return
1189     // The resident process won't let him die
1190     if (appRecord->IsKeepAliveApp()) {
1191         return;
1192     }
1193 
1194     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1195     if (pid > 0) {
1196         std::list<pid_t> pids;
1197         pids.push_back(pid);
1198         appRecord->ScheduleProcessSecurityExit();
1199         if (!WaitForRemoteProcessExit(pids, SystemTimeMillisecond())) {
1200             int32_t result = KillProcessByPid(pid);
1201             if (result < 0) {
1202                 HILOG_ERROR("KillProcessByAbilityToken kill process is fail");
1203                 return;
1204             }
1205         }
1206     }
1207 }
1208 
KillProcessesByUserId(int32_t userId)1209 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId)
1210 {
1211     if (!appRunningManager_) {
1212         HILOG_ERROR("appRunningManager_ is nullptr");
1213         return;
1214     }
1215 
1216     int64_t startTime = SystemTimeMillisecond();
1217     std::list<pid_t> pids;
1218     if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
1219         HILOG_INFO("The process corresponding to the userId did not start");
1220         return;
1221     }
1222     if (WaitForRemoteProcessExit(pids, startTime)) {
1223         HILOG_INFO("The remote process exited successfully ");
1224         return;
1225     }
1226     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1227         auto result = KillProcessByPid(*iter);
1228         if (result < 0) {
1229             HILOG_ERROR("KillProcessByPid is failed. pid: %{public}d", *iter);
1230             return;
1231         }
1232     }
1233 }
1234 
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)1235 void AppMgrServiceInner::StartAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1236     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<AppRunningRecord> &appRecord,
1237     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1238 {
1239     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1240     HILOG_INFO("already create appRecord, just start ability");
1241     if (!appRecord) {
1242         HILOG_ERROR("appRecord is null");
1243         return;
1244     }
1245 
1246     if (want) {
1247         want->SetParam(DLP_PARAMS_SECURITY_FLAG, appRecord->GetSecurityFlag());
1248     }
1249 
1250     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
1251     if (abilityInfo->launchMode == LaunchMode::SINGLETON && ability != nullptr) {
1252         HILOG_WARN("same ability info in singleton launch mode, will not add ability");
1253         return;
1254     }
1255 
1256     if (ability && preToken) {
1257         HILOG_ERROR("Ability is already started");
1258         ability->SetPreToken(preToken);
1259         return;
1260     }
1261 
1262     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
1263     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1264     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
1265     if (!moduleRecord) {
1266         HILOG_ERROR("add moduleRecord failed");
1267         return;
1268     }
1269 
1270     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
1271     if (!ability) {
1272         HILOG_ERROR("add ability failed");
1273         return;
1274     }
1275 
1276     if (preToken != nullptr) {
1277         ability->SetPreToken(preToken);
1278     }
1279 
1280     ApplicationState appState = appRecord->GetState();
1281     if (appState == ApplicationState::APP_STATE_CREATE) {
1282         HILOG_ERROR("in create state, don't launch ability");
1283         return;
1284     }
1285     appRecord->LaunchAbility(ability);
1286 }
1287 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const1288 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
1289     const sptr<IRemoteObject> &abilityToken) const
1290 {
1291     if (!appRunningManager_) {
1292         HILOG_ERROR("appRunningManager_ is nullptr");
1293         return nullptr;
1294     }
1295 
1296     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
1297 }
1298 
AbilityTerminated(const sptr<IRemoteObject> & token)1299 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
1300 {
1301     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1302     HILOG_DEBUG("Terminate ability come.");
1303     if (!token) {
1304         HILOG_ERROR("Terminate ability error, token is null!");
1305         return;
1306     }
1307 
1308     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
1309     if (!appRecord) {
1310         HILOG_ERROR("Terminate ability error, appRecord is not exist!");
1311         return;
1312     }
1313 
1314     appRecord->AbilityTerminated(token);
1315 }
1316 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const1317 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
1318 {
1319     if (appRunningManager_ == nullptr) {
1320         HILOG_ERROR("appRunningManager is nullptr");
1321         return nullptr;
1322     }
1323     const auto&& appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
1324     const auto& iter = appRunningRecordMap.find(recordId);
1325     return iter != appRunningRecordMap.end() ? iter->second : nullptr;
1326 }
1327 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp)1328 void AppMgrServiceInner::OnAppStateChanged(
1329     const std::shared_ptr<AppRunningRecord> &appRecord, const ApplicationState state, bool needNotifyApp)
1330 {
1331     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1332     if (!appRecord) {
1333         HILOG_ERROR("OnAppStateChanged come, app record is null");
1334         return;
1335     }
1336 
1337     HILOG_DEBUG("OnAppStateChanged begin, bundleName is %{public}s, state:%{public}d",
1338         appRecord->GetBundleName().c_str(), static_cast<int32_t>(state));
1339     for (const auto &callback : appStateCallbacks_) {
1340         if (callback != nullptr) {
1341             callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
1342         }
1343     }
1344 
1345     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStateChanged(appRecord, state, needNotifyApp);
1346 }
1347 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1348 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
1349     const ApplicationState state)
1350 {
1351     AppProcessData processData;
1352     auto appInfoList = appRecord->GetAppInfoList();
1353     for (const auto &list : appInfoList) {
1354         AppData data;
1355         data.appName = list->name;
1356         data.uid = list->uid;
1357         processData.appDatas.push_back(data);
1358     }
1359     processData.processName = appRecord->GetProcessName();
1360     processData.pid = appRecord->GetPriorityObject()->GetPid();
1361     processData.appState = state;
1362     processData.isFocused = appRecord->GetFocusFlag();
1363     return processData;
1364 }
1365 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)1366 void AppMgrServiceInner::OnAbilityStateChanged(
1367     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
1368 {
1369     if (!ability) {
1370         HILOG_ERROR("ability is null");
1371         return;
1372     }
1373     for (const auto &callback : appStateCallbacks_) {
1374         if (callback != nullptr) {
1375             callback->OnAbilityRequestDone(ability->GetToken(), state);
1376         }
1377     }
1378 }
1379 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility)1380 void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility)
1381 {
1382     DelayedSingleton<AppStateObserverManager>::GetInstance()->StateChangedNotifyObserver(abilityStateData, isAbility);
1383 }
1384 
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)1385 void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags,
1386                                       const std::shared_ptr<AppRunningRecord> &appRecord, const int uid,
1387                                       const std::string &bundleName, const int32_t bundleIndex)
1388 {
1389     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1390     if (!remoteClientManager_->GetSpawnClient() || !appRecord) {
1391         HILOG_ERROR("appSpawnClient or appRecord is null");
1392         return;
1393     }
1394 
1395     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
1396     if (bundleMgr_ == nullptr) {
1397         HILOG_ERROR("GetBundleManager fail");
1398         return;
1399     }
1400 
1401     auto userId = GetUserIdByUid(uid);
1402     BundleInfo bundleInfo;
1403     bool bundleMgrResult;
1404     if (bundleIndex == 0) {
1405         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetBundleInfo");
1406         bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfo(bundleName,
1407             BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION, bundleInfo, userId));
1408     } else {
1409         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetSandboxBundleInfo");
1410         bundleMgrResult = (IN_PROCESS_CALL(bundleMgr_->GetSandboxBundleInfo(bundleName,
1411             bundleIndex, userId, bundleInfo)) == 0);
1412     }
1413 
1414     if (!bundleMgrResult) {
1415         HILOG_ERROR("GetBundleInfo is fail");
1416         return;
1417     }
1418 
1419     bool hasAccessBundleDirReq = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
1420         [] (const auto &reqPermission) {
1421             if (PERMISSION_ACCESS_BUNDLE_DIR == reqPermission) {
1422                 return true;
1423             }
1424 
1425             return false;
1426         });
1427     uint8_t setAllowInternet = 0;
1428     uint8_t allowInternet = 1;
1429     auto token = bundleInfo.applicationInfo.accessTokenId;
1430     {
1431         // Add TRACE
1432         HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::VerifyAccessToken");
1433         int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_INTERNET);
1434         if (result != Security::AccessToken::PERMISSION_GRANTED) {
1435             setAllowInternet = 1;
1436             allowInternet = 0;
1437         }
1438 
1439         if (hasAccessBundleDirReq) {
1440             int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_ACCESS_BUNDLE_DIR);
1441             if (result != Security::AccessToken::PERMISSION_GRANTED) {
1442                 HILOG_ERROR("StartProcess PERMISSION_ACCESS_BUNDLE_DIR NOT GRANTED");
1443                 hasAccessBundleDirReq = false;
1444             }
1445         }
1446     }
1447 
1448     AppSpawnStartMsg startMsg;
1449     startMsg.uid = bundleInfo.uid;
1450     startMsg.gid = bundleInfo.gid;
1451     startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId;
1452     startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel;
1453     startMsg.bundleName = bundleName;
1454     startMsg.renderParam = RENDER_PARAM;
1455     startMsg.flags = startFlags;
1456     startMsg.bundleIndex = bundleIndex;
1457     startMsg.setAllowInternet = setAllowInternet;
1458     startMsg.allowInternet = allowInternet;
1459     if (hasAccessBundleDirReq) {
1460         startMsg.flags = startMsg.flags | APP_ACCESS_BUNDLE_DIR;
1461     }
1462 
1463     HILOG_DEBUG("Start process, apl is %{public}s, bundleName is %{public}s, startFlags is %{public}d.",
1464         startMsg.apl.c_str(), bundleName.c_str(), startFlags);
1465 
1466     bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleGidsByUid(bundleName, uid, startMsg.gids));
1467     if (!bundleMgrResult) {
1468         HILOG_ERROR("GetBundleGids is fail");
1469         return;
1470     }
1471 
1472     startMsg.procName = processName;
1473     startMsg.soPath = SO_PATH;
1474 
1475     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
1476     pid_t pid = 0;
1477     ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
1478     if (FAILED(errCode)) {
1479         HILOG_ERROR("failed to spawn new app process, errCode %{public}08x", errCode);
1480         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1481         return;
1482     }
1483     HILOG_INFO("Start process success, pid is %{public}d, processName is %{public}s.", pid, processName.c_str());
1484     appRecord->GetPriorityObject()->SetPid(pid);
1485     appRecord->SetUid(startMsg.uid);
1486     appRecord->SetStartMsg(startMsg);
1487     appRecord->SetAppMgrServiceInner(weak_from_this());
1488     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false);
1489     AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
1490     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessCreated(appRecord);
1491     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
1492 }
1493 
RemoveAppFromRecentList(const std::string & appName,const std::string & processName)1494 void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, const std::string &processName)
1495 {
1496     int64_t startTime = 0;
1497     std::list<pid_t> pids;
1498     auto appTaskInfo = appProcessManager_->GetAppTaskInfoByProcessName(appName, processName);
1499     if (!appTaskInfo) {
1500         return;
1501     }
1502     auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
1503     if (!appRecord) {
1504         appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
1505         return;
1506     }
1507 
1508     // Do not delete resident processes, before exec ScheduleProcessSecurityExit
1509     if (appRecord->IsKeepAliveApp()) {
1510         return;
1511     }
1512 
1513     startTime = SystemTimeMillisecond();
1514     pids.push_back(appTaskInfo->GetPid());
1515     appRecord->ScheduleProcessSecurityExit();
1516     if (!WaitForRemoteProcessExit(pids, startTime)) {
1517         int32_t result = KillProcessByPid(appTaskInfo->GetPid());
1518         if (result < 0) {
1519             HILOG_ERROR("RemoveAppFromRecentList kill process is fail");
1520             return;
1521         }
1522     }
1523     appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
1524 }
1525 
GetRecentAppList() const1526 const std::list<const std::shared_ptr<AppTaskInfo>> &AppMgrServiceInner::GetRecentAppList() const
1527 {
1528     return appProcessManager_->GetRecentAppList();
1529 }
1530 
ClearRecentAppList()1531 void AppMgrServiceInner::ClearRecentAppList()
1532 {
1533     int64_t startTime = 0;
1534     std::list<pid_t> pids;
1535     if (GetAllPids(pids)) {
1536         return;
1537     }
1538 
1539     startTime = SystemTimeMillisecond();
1540     if (WaitForRemoteProcessExit(pids, startTime)) {
1541         appProcessManager_->ClearRecentAppList();
1542         return;
1543     }
1544     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1545         int32_t result = KillProcessByPid(*iter);
1546         if (result < 0) {
1547             HILOG_ERROR("ClearRecentAppList kill process is fail");
1548             return;
1549         }
1550     }
1551     appProcessManager_->ClearRecentAppList();
1552 }
1553 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess)1554 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess)
1555 {
1556     HILOG_ERROR("On remote died.");
1557     if (isRenderProcess) {
1558         OnRenderRemoteDied(remote);
1559         return;
1560     }
1561 
1562     auto appRecord = appRunningManager_->OnRemoteDied(remote);
1563     if (!appRecord) {
1564         return;
1565     }
1566 
1567     ClearAppRunningData(appRecord, false);
1568 }
1569 
ClearAppRunningData(const std::shared_ptr<AppRunningRecord> & appRecord,bool containsApp)1570 void AppMgrServiceInner::ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord, bool containsApp)
1571 {
1572     if (!appRecord) {
1573         return;
1574     }
1575 
1576     if (containsApp) {
1577         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1578     }
1579 
1580     FinishUserTestLocked("App died", -1, appRecord);
1581     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_REMOTE_DIED);
1582 
1583     for (const auto &item : appRecord->GetAbilities()) {
1584         const auto &abilityRecord = item.second;
1585         appRecord->StateChangedNotifyObserver(abilityRecord,
1586             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true);
1587     }
1588     RemoveAppFromRecentListById(appRecord->GetRecordId());
1589     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
1590 
1591     // kill render if exist.
1592     auto renderRecord = appRecord->GetRenderRecord();
1593     if (renderRecord && renderRecord->GetPid() > 0) {
1594         HILOG_DEBUG("Kill render process when host died.");
1595         KillProcessByPid(renderRecord->GetPid());
1596         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
1597     }
1598 
1599     if (appRecord->IsKeepAliveApp()) {
1600         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
1601             innerService->RestartResidentProcess(appRecord);
1602         };
1603         if (appRecord->CanRestartResidentProc()) {
1604             if (!eventHandler_) {
1605                 HILOG_ERROR("eventHandler_ is nullptr");
1606                 return;
1607             }
1608             eventHandler_->PostTask(restartProcess, "RestartResidentProcess");
1609         } else {
1610             auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
1611                 return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
1612             };
1613             auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(),
1614                 findRestartResidentTask);
1615             if (findIter != restartResedentTaskList_.end()) {
1616                 HILOG_WARN("The restart app task has been registered.");
1617                 return;
1618             }
1619             restartResedentTaskList_.emplace_back(appRecord);
1620             HILOG_INFO("PostRestartResidentProcessDelayTask.");
1621             eventHandler_->PostTask(restartProcess, "RestartResidentProcessDelayTask", RESTART_INTERVAL_TIME);
1622         }
1623     }
1624 }
1625 
PushAppFront(const int32_t recordId)1626 void AppMgrServiceInner::PushAppFront(const int32_t recordId)
1627 {
1628     appProcessManager_->PushAppFront(recordId);
1629 }
1630 
RemoveAppFromRecentListById(const int32_t recordId)1631 void AppMgrServiceInner::RemoveAppFromRecentListById(const int32_t recordId)
1632 {
1633     appProcessManager_->RemoveAppFromRecentListById(recordId);
1634 }
1635 
AddAppToRecentList(const std::string & appName,const std::string & processName,const pid_t pid,const int32_t recordId)1636 void AppMgrServiceInner::AddAppToRecentList(
1637     const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId)
1638 {
1639     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1640     appProcessManager_->AddAppToRecentList(appName, processName, pid, recordId);
1641 }
1642 
GetAppTaskInfoById(const int32_t recordId) const1643 const std::shared_ptr<AppTaskInfo> AppMgrServiceInner::GetAppTaskInfoById(const int32_t recordId) const
1644 {
1645     return appProcessManager_->GetAppTaskInfoById(recordId);
1646 }
1647 
AddAppDeathRecipient(const pid_t pid,const sptr<AppDeathRecipient> & appDeathRecipient) const1648 void AppMgrServiceInner::AddAppDeathRecipient(const pid_t pid, const sptr<AppDeathRecipient> &appDeathRecipient) const
1649 {
1650     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1651     std::shared_ptr<AppRunningRecord> appRecord = GetAppRunningRecordByPid(pid);
1652     if (appRecord) {
1653         appRecord->SetAppDeathRecipient(appDeathRecipient);
1654     }
1655 }
1656 
HandleTimeOut(const InnerEvent::Pointer & event)1657 void AppMgrServiceInner::HandleTimeOut(const InnerEvent::Pointer &event)
1658 {
1659     HILOG_INFO("handle time out");
1660     if (!appRunningManager_ || event == nullptr) {
1661         HILOG_ERROR("appRunningManager or event is nullptr");
1662         return;
1663     }
1664 
1665     // check libc.hook_mode
1666     const int bufferLen = 128;
1667     char paramOutBuf[bufferLen] = {0};
1668     const char *hook_mode = "startup:";
1669     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
1670     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
1671         HILOG_DEBUG("HandleTimeOut, Hook_mode: no handle time out");
1672         return;
1673     }
1674 
1675     switch (event->GetInnerEventId()) {
1676         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
1677             appRunningManager_->HandleTerminateTimeOut(event->GetParam());
1678             break;
1679         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
1680             SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1681             HandleTerminateApplicationTimeOut(event->GetParam());
1682             break;
1683         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
1684         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
1685             SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1686             HandleAddAbilityStageTimeOut(event->GetParam());
1687             break;
1688         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
1689             SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1690             HandleStartSpecifiedAbilityTimeOut(event->GetParam());
1691             break;
1692         default:
1693             break;
1694     }
1695 }
1696 
SetEventHandler(const std::shared_ptr<AMSEventHandler> & handler)1697 void AppMgrServiceInner::SetEventHandler(const std::shared_ptr<AMSEventHandler> &handler)
1698 {
1699     eventHandler_ = handler;
1700 }
1701 
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)1702 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
1703 {
1704     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1705     HILOG_INFO("%{public}s called", __func__);
1706     if (!appRunningManager_) {
1707         HILOG_ERROR("appRunningManager_ is nullptr");
1708         return;
1709     }
1710     appRunningManager_->HandleAbilityAttachTimeOut(token);
1711 }
1712 
PrepareTerminate(const sptr<IRemoteObject> & token)1713 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token)
1714 {
1715     HILOG_INFO("AppMgrService prepare to terminate the ability.");
1716     if (!appRunningManager_) {
1717         HILOG_ERROR("appRunningManager_ is nullptr");
1718         return;
1719     }
1720     appRunningManager_->PrepareTerminate(token);
1721 }
1722 
HandleTerminateApplicationTimeOut(const int64_t eventId)1723 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId)
1724 {
1725     HILOG_INFO("handle terminate application time out");
1726     if (!appRunningManager_) {
1727         HILOG_ERROR("appRunningManager_ is nullptr");
1728         return;
1729     }
1730     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
1731     TerminateApplication(appRecord);
1732 }
1733 
TerminateApplication(const std::shared_ptr<AppRunningRecord> & appRecord)1734 void AppMgrServiceInner::TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
1735 {
1736     if (!appRecord) {
1737         HILOG_ERROR("appRecord is nullptr");
1738         return;
1739     }
1740     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
1741     appRecord->RemoveAppDeathRecipient();
1742     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT);
1743     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false);
1744     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1745     if (pid > 0) {
1746         auto timeoutTask = [pid, innerService = shared_from_this()]() {
1747             HILOG_INFO("KillProcessByPid %{public}d", pid);
1748             int32_t result = innerService->KillProcessByPid(pid);
1749             if (result < 0) {
1750                 HILOG_ERROR("KillProcessByPid kill process is fail");
1751                 return;
1752             }
1753         };
1754         if (!eventHandler_) {
1755             HILOG_ERROR("eventHandler_ is nullptr");
1756             return;
1757         }
1758         eventHandler_->PostTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
1759     }
1760     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1761     RemoveAppFromRecentListById(appRecord->GetRecordId());
1762     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
1763 }
1764 
HandleAddAbilityStageTimeOut(const int64_t eventId)1765 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId)
1766 {
1767     HILOG_INFO("called add ability stage info time out!");
1768     if (!appRunningManager_) {
1769         HILOG_ERROR("appRunningManager_ is nullptr");
1770         return;
1771     }
1772     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
1773     if (!appRecord) {
1774         HILOG_ERROR("appRecord is nullptr");
1775         return;
1776     }
1777 
1778     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
1779         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
1780     }
1781 
1782     KillApplicationByRecord(appRecord);
1783 }
1784 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)1785 void AppMgrServiceInner::GetRunningProcessInfoByToken(
1786     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
1787 {
1788     HILOG_INFO("%{public}s called", __func__);
1789     if (!CheckGetRunningInfoPermission()) {
1790         return;
1791     }
1792 
1793     appRunningManager_->GetRunningProcessInfoByToken(token, info);
1794 }
1795 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info) const1796 void AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const
1797 {
1798     HILOG_INFO("%{public}s called", __func__);
1799     if (!CheckGetRunningInfoPermission()) {
1800         return;
1801     }
1802 
1803     appRunningManager_->GetRunningProcessInfoByPid(pid, info);
1804 }
1805 
CheckGetRunningInfoPermission() const1806 bool AppMgrServiceInner::CheckGetRunningInfoPermission() const
1807 {
1808     if (!appRunningManager_) {
1809         HILOG_ERROR("appRunningManager_ is nullptr");
1810         return false;
1811     }
1812 
1813     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1814     if (!isPerm) {
1815         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1816         return false;
1817     }
1818 
1819     return true;
1820 }
1821 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)1822 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
1823 {
1824     HILOG_INFO("%{public}s called", __func__);
1825 
1826     HILOG_INFO("bundle info size: [%{public}zu]", infos.size());
1827     StartResidentProcess(infos, -1, true);
1828 }
1829 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount,bool isEmptyKeepAliveApp)1830 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount,
1831     bool isEmptyKeepAliveApp)
1832 {
1833     HILOG_INFO("start resident process");
1834     if (infos.empty()) {
1835         HILOG_ERROR("infos is empty!");
1836         return;
1837     }
1838 
1839     if (!appRunningManager_) {
1840         HILOG_ERROR("appRunningManager_ is nullptr");
1841         return;
1842     }
1843 
1844     for (auto &bundle : infos) {
1845         HILOG_INFO("processName = [%{public}s]", bundle.applicationInfo.process.c_str());
1846         if (bundle.applicationInfo.process.empty()) {
1847             continue;
1848         }
1849         auto processName = bundle.applicationInfo.process;
1850         // Inspection records
1851         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
1852             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
1853         if (appRecord) {
1854             HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
1855             continue;
1856         }
1857         HILOG_INFO("Start empty resident process, processName = [%{public}s]", processName.c_str());
1858         StartEmptyResidentProcess(bundle, processName, restartCount, isEmptyKeepAliveApp);
1859     }
1860 }
1861 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount,bool isEmptyKeepAliveApp)1862 void AppMgrServiceInner::StartEmptyResidentProcess(
1863     const BundleInfo &info, const std::string &processName, int restartCount, bool isEmptyKeepAliveApp)
1864 {
1865     HILOG_INFO("start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
1866     if (!CheckRemoteClient() || !appRunningManager_) {
1867         HILOG_INFO("Failed to start resident process!");
1868         return;
1869     }
1870 
1871     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
1872     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
1873     if (!appRecord) {
1874         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
1875         return;
1876     }
1877 
1878     StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, appInfo->bundleName, 0);
1879 
1880     // If it is empty, the startup failed
1881     if (!appRecord) {
1882         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
1883         return;
1884     }
1885 
1886     appRecord->SetKeepAliveAppState(true, isEmptyKeepAliveApp);
1887 
1888     if (restartCount > 0) {
1889         HILOG_INFO("StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount);
1890         appRecord->SetRestartResidentProcCount(restartCount);
1891     }
1892 
1893     appRecord->SetEventHandler(eventHandler_);
1894     appRecord->AddModules(appInfo, info.hapModuleInfos);
1895     HILOG_INFO("StartEmptyResidentProcess of pid : [%{public}d], ", appRecord->GetPriorityObject()->GetPid());
1896 }
1897 
CheckRemoteClient()1898 bool AppMgrServiceInner::CheckRemoteClient()
1899 {
1900     if (!remoteClientManager_) {
1901         HILOG_ERROR("remoteClientManager_ is null");
1902         return false;
1903     }
1904 
1905     if (!remoteClientManager_->GetSpawnClient()) {
1906         HILOG_ERROR("appSpawnClient is null");
1907         return false;
1908     }
1909 
1910     if (!remoteClientManager_->GetBundleManager()) {
1911         HILOG_ERROR("GetBundleManager fail");
1912         return false;
1913     }
1914     return true;
1915 }
1916 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)1917 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
1918 {
1919     if (appRecord == nullptr) {
1920         HILOG_ERROR("Restart resident process failed, the appRecord is nullptr.");
1921         return;
1922     }
1923     struct timespec t;
1924     t.tv_sec = 0;
1925     t.tv_nsec = 0;
1926     clock_gettime(CLOCK_MONOTONIC, &t);
1927     appRecord->SetRestartTimeMillis(static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS));
1928     appRecord->DecRestartResidentProcCount();
1929 
1930     auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
1931         return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
1932     };
1933     auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(), findRestartResidentTask);
1934     if (findIter != restartResedentTaskList_.end()) {
1935         restartResedentTaskList_.erase(findIter);
1936     }
1937 
1938     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
1939         HILOG_ERROR("restart resident process failed!");
1940         return;
1941     }
1942 
1943     auto bundleMgr = remoteClientManager_->GetBundleManager();
1944     BundleInfo bundleInfo;
1945     auto callerUid = IPCSkeleton::GetCallingUid();
1946     auto userId = GetUserIdByUid(callerUid);
1947     if (!IN_PROCESS_CALL(
1948         bundleMgr->GetBundleInfo(appRecord->GetBundleName(), BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
1949         HILOG_ERROR("GetBundleInfo fail");
1950         return;
1951     }
1952     std::vector<BundleInfo> infos;
1953     infos.emplace_back(bundleInfo);
1954     HILOG_INFO("the resident process [%{public}s] remaining restarts num is [%{public}d]",
1955         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
1956     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount(), appRecord->IsEmptyKeepAliveApp());
1957 }
1958 
NotifyAppStatus(const std::string & bundleName,const std::string & eventData)1959 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData)
1960 {
1961     HILOG_INFO("%{public}s called, bundle name is %{public}s, event is %{public}s",
1962         __func__, bundleName.c_str(), eventData.c_str());
1963     Want want;
1964     want.SetAction(eventData);
1965     ElementName element;
1966     element.SetBundleName(bundleName);
1967     want.SetElement(element);
1968     want.SetParam(Constants::USER_ID, 0);
1969     EventFwk::CommonEventData commonData {want};
1970     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1971 }
1972 
NotifyAppStatusByCallerUid(const std::string & bundleName,const int32_t userId,const int32_t callerUid,const std::string & eventData)1973 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t userId,
1974     const int32_t callerUid, const std::string &eventData)
1975 {
1976     HILOG_INFO("%{public}s called, bundle name is %{public}s, , userId is %{public}d, event is %{public}s",
1977         __func__, bundleName.c_str(), userId, eventData.c_str());
1978     Want want;
1979     want.SetAction(eventData);
1980     ElementName element;
1981     element.SetBundleName(bundleName);
1982     want.SetElement(element);
1983     want.SetParam(Constants::USER_ID, userId);
1984     want.SetParam(Constants::UID, callerUid);
1985     EventFwk::CommonEventData commonData {want};
1986     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1987 }
1988 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)1989 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(
1990     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
1991 {
1992     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterApplicationStateObserver(
1993         observer, bundleNameList);
1994 }
1995 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)1996 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
1997 {
1998     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterApplicationStateObserver(observer);
1999 }
2000 
GetForegroundApplications(std::vector<AppStateData> & list)2001 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
2002 {
2003     HILOG_INFO("%{public}s, begin.", __func__);
2004     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2005     if (!isPerm) {
2006         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2007         return ERR_PERMISSION_DENIED;
2008     }
2009 
2010     appRunningManager_->GetForegroundApplications(list);
2011     return ERR_OK;
2012 }
2013 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)2014 int AppMgrServiceInner::StartUserTestProcess(
2015     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
2016 {
2017     HILOG_INFO("Enter");
2018     if (!observer) {
2019         HILOG_ERROR("observer nullptr.");
2020         return ERR_INVALID_VALUE;
2021     }
2022     if (!appRunningManager_) {
2023         HILOG_ERROR("appRunningManager_ is nullptr");
2024         return ERR_INVALID_VALUE;
2025     }
2026 
2027     std::string bundleName = want.GetStringParam("-b");
2028     if (bundleName.empty()) {
2029         HILOG_ERROR("Invalid bundle name");
2030         return ERR_INVALID_VALUE;
2031     }
2032 
2033     if (KillApplicationByUserIdLocked(bundleName, userId)) {
2034         HILOG_ERROR("Failed to kill the application");
2035         return ERR_INVALID_VALUE;
2036     }
2037 
2038     HapModuleInfo hapModuleInfo;
2039     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
2040         HILOG_ERROR("Failed to get HapModuleInfo for TestRunner");
2041         return ERR_INVALID_VALUE;
2042     }
2043 
2044     std::string processName;
2045     MakeProcessName(std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo, processName);
2046     HILOG_INFO("processName = [%{public}s]", processName.c_str());
2047 
2048     // Inspection records
2049     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
2050         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
2051     if (appRecord) {
2052         HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
2053         return ERR_INVALID_VALUE;
2054     }
2055 
2056     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
2057 }
2058 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)2059 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2060     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
2061 {
2062     HILOG_INFO("Enter");
2063     if (!observer) {
2064         HILOG_ERROR("observer nullptr.");
2065         return ERR_INVALID_VALUE;
2066     }
2067 
2068     bool moduleJson = false;
2069     if (!bundleInfo.hapModuleInfos.empty()) {
2070         moduleJson = bundleInfo.hapModuleInfos.back().isModuleJson;
2071     }
2072     if (moduleJson) {
2073         std::string moduleName = want.GetStringParam("-m");
2074         if (moduleName.empty()) {
2075             UserTestAbnormalFinish(observer, "No module name is specified.");
2076             return ERR_INVALID_VALUE;
2077         }
2078 
2079         bool found = false;
2080         for (auto item : bundleInfo.hapModuleInfos) {
2081             if (item.moduleName == moduleName) {
2082                 hapModuleInfo = item;
2083                 found = true;
2084                 break;
2085             }
2086         }
2087         if (!found) {
2088             UserTestAbnormalFinish(observer, "The specified module name is not found.");
2089             return ERR_INVALID_VALUE;
2090         }
2091     }
2092     return ERR_OK;
2093 }
2094 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)2095 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
2096 {
2097     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
2098     if (!observerProxy) {
2099         HILOG_ERROR("Failed to get ITestObserver proxy");
2100         return ERR_INVALID_VALUE;
2101     }
2102     observerProxy->TestFinished(msg, -1);
2103     return ERR_OK;
2104 }
2105 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)2106 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2107     const BundleInfo &info, const std::string &processName, const int userId)
2108 {
2109     HILOG_INFO("enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
2110     if (!CheckRemoteClient() || !appRunningManager_) {
2111         HILOG_ERROR("Failed to start the process being tested!");
2112         return ERR_INVALID_VALUE;
2113     }
2114 
2115     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
2116     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
2117     if (!appRecord) {
2118         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
2119         return ERR_INVALID_VALUE;
2120     }
2121 
2122     auto isDebug = want.GetBoolParam("debugApp", false);
2123     HILOG_INFO("Set Debug : %{public}s", (isDebug ? "true" : "false"));
2124     appRecord->SetDebugApp(isDebug);
2125     if (want.GetBoolParam(COLD_START, false)) {
2126         appRecord->SetDebugApp(true);
2127     }
2128 
2129     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
2130     if (!testRecord) {
2131         HILOG_ERROR("Failed to make UserTestRecord!");
2132         return ERR_INVALID_VALUE;
2133     }
2134     testRecord->want = want;
2135     testRecord->observer = observer;
2136     testRecord->isFinished = false;
2137     testRecord->userId = userId;
2138     appRecord->SetUserTestInfo(testRecord);
2139 
2140     int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2141     uint32_t startFlags = 0x0;
2142     if (info.applicationInfo.debug) {
2143         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
2144     }
2145     StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, appInfo->bundleName, bundleIndex);
2146 
2147     // If it is empty, the startup failed
2148     if (!appRecord) {
2149         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
2150         return ERR_INVALID_VALUE;
2151     }
2152 
2153     appRecord->SetEventHandler(eventHandler_);
2154     appRecord->AddModules(appInfo, info.hapModuleInfos);
2155     HILOG_INFO("StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid());
2156 
2157     return ERR_OK;
2158 }
2159 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName,const pid_t & pid)2160 int AppMgrServiceInner::FinishUserTest(
2161     const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid)
2162 {
2163     HILOG_INFO("Enter");
2164     if (bundleName.empty()) {
2165         HILOG_ERROR("Invalid bundle name.");
2166         return ERR_INVALID_VALUE;
2167     }
2168     auto appRecord = GetAppRunningRecordByPid(pid);
2169     if (!appRecord) {
2170         HILOG_ERROR("no such appRecord");
2171         return ERR_INVALID_VALUE;
2172     }
2173 
2174     auto userTestRecord = appRecord->GetUserTestInfo();
2175     if (!userTestRecord) {
2176         HILOG_ERROR("unstart user test");
2177         return ERR_INVALID_VALUE;
2178     }
2179 
2180     FinishUserTestLocked(msg, resultCode, appRecord);
2181 
2182     int ret = KillApplicationByUserIdLocked(bundleName, userTestRecord->userId);
2183     if (ret) {
2184         HILOG_ERROR("Failed to kill process.");
2185         return ret;
2186     }
2187 
2188     return ERR_OK;
2189 }
2190 
FinishUserTestLocked(const std::string & msg,const int64_t & resultCode,const std::shared_ptr<AppRunningRecord> & appRecord)2191 int AppMgrServiceInner::FinishUserTestLocked(
2192     const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord)
2193 {
2194     HILOG_INFO("Enter");
2195     if (!appRecord) {
2196         HILOG_ERROR("Invalid appRecord");
2197         return ERR_INVALID_VALUE;
2198     }
2199 
2200     std::unique_lock<std::mutex> lock(userTestLock_);
2201     auto userTestRecord = appRecord->GetUserTestInfo();
2202     if (!userTestRecord) {
2203         HILOG_WARN("not start user test");
2204         return ERR_INVALID_VALUE;
2205     }
2206     if (!userTestRecord->isFinished) {
2207         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
2208         if (!observerProxy) {
2209             HILOG_ERROR("Failed to get ITestObserver proxy");
2210             return ERR_INVALID_VALUE;
2211         }
2212         observerProxy->TestFinished(msg, resultCode);
2213 
2214         userTestRecord->isFinished = true;
2215     }
2216 
2217     return ERR_OK;
2218 }
2219 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo)2220 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)
2221 {
2222     HILOG_DEBUG("Start specified ability.");
2223     if (!CheckRemoteClient()) {
2224         return;
2225     }
2226 
2227     BundleInfo bundleInfo;
2228     HapModuleInfo hapModuleInfo;
2229     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
2230 
2231     int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2232     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
2233         return;
2234     }
2235 
2236     std::string processName;
2237     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
2238     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, processName);
2239 
2240     std::vector<HapModuleInfo> hapModules;
2241     hapModules.emplace_back(hapModuleInfo);
2242 
2243     std::shared_ptr<AppRunningRecord> appRecord;
2244     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
2245     if (!appRecord) {
2246         // new app record
2247         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
2248         if (!appRecord) {
2249             HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2250             return;
2251         }
2252         appRecord->SetEventHandler(eventHandler_);
2253         appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
2254             AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT);
2255         uint32_t startFlags = BuildStartFlags(want, abilityInfo);
2256         int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2257         StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, appInfo->bundleName,
2258             bundleIndex);
2259 
2260         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2261         appRecord->AddModules(appInfo, hapModules);
2262     } else {
2263         HILOG_DEBUG("process is exist");
2264         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2265         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
2266         if (!moduleRecord) {
2267             HILOG_DEBUG("module record is nullptr, add modules");
2268             appRecord->AddModules(appInfo, hapModules);
2269             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
2270         } else {
2271             HILOG_DEBUG("schedule accept want");
2272             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
2273         }
2274     }
2275 }
2276 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)2277 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
2278 {
2279     if (!response) {
2280         HILOG_ERROR("response is nullptr, register failed.");
2281         return;
2282     }
2283 
2284     pid_t callingPid = IPCSkeleton::GetCallingPid();
2285     pid_t pid = getpid();
2286     if (callingPid != pid) {
2287         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
2288         return;
2289     }
2290 
2291     startSpecifiedAbilityResponse_ = response;
2292 }
2293 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)2294 void AppMgrServiceInner::ScheduleAcceptWantDone(
2295     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
2296 {
2297     HILOG_DEBUG("Schedule accept want done, flag: %{public}s", flag.c_str());
2298 
2299     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
2300     if (!appRecord) {
2301         HILOG_ERROR("Get app record failed.");
2302         return;
2303     }
2304     appRecord->ScheduleAcceptWantDone();
2305 
2306     if (startSpecifiedAbilityResponse_) {
2307         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag);
2308     }
2309 }
2310 
HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)2311 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)
2312 {
2313     HILOG_DEBUG("called start specified ability time out!");
2314     if (!appRunningManager_) {
2315         HILOG_ERROR("appRunningManager_ is nullptr");
2316         return;
2317     }
2318 
2319     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2320     if (!appRecord) {
2321         HILOG_ERROR("appRecord is nullptr");
2322         return;
2323     }
2324 
2325     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
2326         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
2327     }
2328 
2329     KillApplicationByRecord(appRecord);
2330 }
2331 
UpdateConfiguration(const Configuration & config)2332 int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config)
2333 {
2334     if (!appRunningManager_) {
2335         HILOG_ERROR("appRunningManager_ is null");
2336         return ERR_INVALID_VALUE;
2337     }
2338 
2339     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
2340     if (ret != ERR_OK) {
2341         return ret;
2342     }
2343 
2344     std::vector<std::string> changeKeyV;
2345     configuration_->CompareDifferent(changeKeyV, config);
2346     HILOG_INFO("changeKeyV size :%{public}zu", changeKeyV.size());
2347     if (changeKeyV.empty()) {
2348         HILOG_ERROR("changeKeyV is empty");
2349         return ERR_INVALID_VALUE;
2350     }
2351     configuration_->Merge(changeKeyV, config);
2352     // all app
2353     int32_t result = appRunningManager_->UpdateConfiguration(config);
2354     if (result != ERR_OK) {
2355         HILOG_ERROR("update error, not notify");
2356         return result;
2357     }
2358     // notify
2359     std::lock_guard<std::recursive_mutex> notifyLock(configurationObserverLock_);
2360     for (auto &observer : configurationObservers_) {
2361         if (observer != nullptr) {
2362             observer->OnConfigurationUpdated(config);
2363         }
2364     }
2365     return result;
2366 }
2367 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)2368 int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
2369 {
2370     HILOG_INFO("AppMgrServiceInner::RegisterConfigurationObserver: called");
2371 
2372     if (observer == nullptr) {
2373         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
2374         return ERR_INVALID_VALUE;
2375     }
2376     std::lock_guard<std::recursive_mutex> registerLock(configurationObserverLock_);
2377     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
2378         [&observer](const sptr<IConfigurationObserver> &item) {
2379             return (item && item->AsObject() == observer->AsObject());
2380         }
2381     );
2382     if (it != configurationObservers_.end()) {
2383         HILOG_ERROR("AppMgrServiceInner::Register error: observer exist");
2384         return ERR_INVALID_VALUE;
2385     }
2386     configurationObservers_.push_back(observer);
2387     return NO_ERROR;
2388 }
2389 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)2390 int32_t AppMgrServiceInner::UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
2391 {
2392     HILOG_INFO("AppMgrServiceInner::UnregisterConfigurationObserver: called");
2393     if (observer == nullptr) {
2394         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
2395         return ERR_INVALID_VALUE;
2396     }
2397     std::lock_guard<std::recursive_mutex> unregisterLock(configurationObserverLock_);
2398     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
2399         [&observer](const sptr<IConfigurationObserver> &item) {
2400             return (item && item->AsObject() == observer->AsObject());
2401         }
2402     );
2403     if (it != configurationObservers_.end()) {
2404         configurationObservers_.erase(it);
2405         return NO_ERROR;
2406     }
2407     HILOG_INFO("AppMgrServiceInner ConfigurationObserver not register");
2408     return ERR_INVALID_VALUE;
2409 }
2410 
InitGlobalConfiguration()2411 void AppMgrServiceInner::InitGlobalConfiguration()
2412 {
2413     if (!configuration_) {
2414         HILOG_ERROR("configuration_ is null");
2415         return;
2416     }
2417 
2418 #ifdef SUPPORT_GRAPHICS
2419     // Currently only this interface is known
2420     auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
2421     HILOG_INFO("current global language is : %{public}s", language.c_str());
2422     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
2423 #endif
2424 
2425     // Assign to default colorMode "light"
2426     HILOG_INFO("current global colorMode is : %{public}s", ConfigurationInner::COLOR_MODE_LIGHT);
2427     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
2428 
2429     // Get input pointer device
2430     std::string hasPointerDevice = system::GetParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "false");
2431     HILOG_INFO("current hasPointerDevice is %{public}s", hasPointerDevice.c_str());
2432     configuration_->AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, hasPointerDevice);
2433 
2434     // Get DeviceType
2435     auto deviceType = GetDeviceType();
2436     HILOG_INFO("current deviceType is %{public}s", deviceType);
2437     configuration_->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType);
2438 }
2439 
GetConfiguration()2440 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
2441 {
2442     return configuration_;
2443 }
2444 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)2445 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
2446 {
2447     HILOG_DEBUG("Kill application by appRecord.");
2448     if (!appRecord || !eventHandler_) {
2449         HILOG_WARN("appRecord or eventHandler_ is nullptr.");
2450         return;
2451     }
2452 
2453     auto pid = appRecord->GetPriorityObject()->GetPid();
2454     appRecord->SetTerminating();
2455     appRecord->ScheduleProcessSecurityExit();
2456 
2457     auto startTime = SystemTimeMillisecond();
2458     std::list<pid_t> pids = {pid};
2459     if (WaitForRemoteProcessExit(pids, startTime)) {
2460         HILOG_INFO("The remote process exited successfully");
2461         return;
2462     }
2463 
2464     auto timeoutTask = [pid, innerService = shared_from_this()]() {
2465         HILOG_INFO("KillProcessByPid %{public}d", pid);
2466         int32_t result = innerService->KillProcessByPid(pid);
2467         if (result < 0) {
2468             HILOG_ERROR("Kill application by app record failed, pid: %{public}d", pid);
2469             return;
2470         }
2471     };
2472     eventHandler_->PostTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
2473 }
2474 
SendHiSysEvent(const int32_t innerEventId,const int64_t eventId)2475 void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_t eventId)
2476 {
2477     HILOG_DEBUG("called AppMgrServiceInner SendHiSysEvent!");
2478     if (!appRunningManager_) {
2479         HILOG_ERROR("appRunningManager_ is nullptr");
2480         return;
2481     }
2482 
2483     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2484     if (!appRecord) {
2485         HILOG_ERROR("appRecord is nullptr");
2486         return;
2487     }
2488     const int bufferLen = 128;
2489     char paramOutBuf[bufferLen] = {0};
2490     const char *hook_mode = "startup:";
2491     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
2492     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
2493         HILOG_DEBUG("SendHiSysEvent, Hook_mode: no handle time out");
2494         return;
2495     }
2496 
2497     std::string eventName = EVENT_NAME_LIFECYCLE_TIMEOUT;
2498     int32_t pid = appRecord->GetPriorityObject()->GetPid();
2499     int32_t uid = appRecord->GetUid();
2500     std::string packageName = appRecord->GetBundleName();
2501     std::string processName = appRecord->GetProcessName();
2502     std::string msg;
2503     switch (innerEventId) {
2504         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
2505             msg = EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
2506             break;
2507         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
2508             msg = EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
2509             break;
2510         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
2511             msg = EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
2512             break;
2513         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
2514             msg = EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
2515             break;
2516         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
2517             msg = EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
2518             break;
2519         default:
2520             msg = EVENT_MESSAGE_DEFAULT;
2521             break;
2522     }
2523 
2524     HILOG_DEBUG("SendHiSysEvent, eventName = %{public}s, uid = %{public}d, pid = %{public}d, \
2525         packageName = %{public}s, processName = %{public}s, msg = %{public}s",
2526         eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
2527 
2528     OHOS::HiviewDFX::HiSysEvent::Write(
2529         OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK,
2530         eventName,
2531         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
2532         EVENT_KEY_PID, pid,
2533         EVENT_KEY_UID, uid,
2534         EVENT_KEY_PACKAGE_NAME, packageName,
2535         EVENT_KEY_PROCESS_NAME, processName,
2536         EVENT_KEY_MESSAGE, msg);
2537 }
2538 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)2539 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
2540 {
2541     auto appRecord = GetAppRunningRecordByPid(pid);
2542     if (!appRecord) {
2543         HILOG_ERROR("no such appRecord");
2544         return ERR_NAME_NOT_FOUND;
2545     }
2546 
2547     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2548     auto callingPid = IPCSkeleton::GetCallingPid();
2549     if (!isSaCall && callingPid != pid) {
2550         HILOG_ERROR("Permission verify failed.");
2551         return ERR_PERMISSION_DENIED;
2552     }
2553     for (auto &item : appRecord->GetAbilities()) {
2554         tokens.emplace_back(item.first);
2555     }
2556     return ERR_OK;
2557 }
2558 
GetApplicationInfoByProcessID(const int pid,AppExecFwk::ApplicationInfo & application,bool & debug)2559 int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application,
2560     bool &debug)
2561 {
2562     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2563     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
2564     if (!isSaCall && !isShellCall) {
2565         HILOG_ERROR("no permissions.");
2566         return ERR_PERMISSION_DENIED;
2567     }
2568     auto appRecord = GetAppRunningRecordByPid(pid);
2569     if (!appRecord) {
2570         HILOG_ERROR("no such appRecord for PID:%{public}d", pid);
2571         return ERR_NAME_NOT_FOUND;
2572     }
2573 
2574     auto info = appRecord->GetApplicationInfo();
2575     if (info == nullptr) {
2576         HILOG_ERROR("ApplicationInfo is nullptr !");
2577         return ERR_NO_INIT;
2578     }
2579     application = *info;
2580     debug = appRecord->IsDebugApp();
2581     return ERR_OK;
2582 }
2583 
VerifyProcessPermission(const std::string & bundleName) const2584 int AppMgrServiceInner::VerifyProcessPermission(const std::string &bundleName) const
2585 {
2586     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2587     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
2588     if (isSaCall || isShellCall) {
2589         return ERR_OK;
2590     }
2591 
2592     if (VerifyAPL()) {
2593         return ERR_OK;
2594     }
2595 
2596     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2597         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
2598     if (isCallingPerm) {
2599         if (AAFwk::PermissionVerification::GetInstance()->IsGatewayCall()) {
2600             return ERR_OK;
2601         }
2602         auto callerPid = IPCSkeleton::GetCallingPid();
2603         auto appRecord = GetAppRunningRecordByPid(callerPid);
2604         if (!appRecord || appRecord->GetBundleName() != bundleName) {
2605             HILOG_ERROR("Permission verification failed.");
2606             return ERR_PERMISSION_DENIED;
2607         }
2608     } else {
2609         HILOG_ERROR("Permission verification failed.");
2610         return ERR_PERMISSION_DENIED;
2611     }
2612 
2613     return ERR_OK;
2614 }
2615 
VerifyProcessPermission(const sptr<IRemoteObject> & token) const2616 int AppMgrServiceInner::VerifyProcessPermission(const sptr<IRemoteObject> &token) const
2617 {
2618     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2619     if (isSaCall) {
2620         return ERR_OK;
2621     }
2622 
2623     if (VerifyAPL()) {
2624         return ERR_OK;
2625     }
2626 
2627     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2628         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
2629     if (isCallingPerm) {
2630         if (AAFwk::PermissionVerification::GetInstance()->IsGatewayCall()) {
2631             return ERR_OK;
2632         }
2633         auto callerUid = IPCSkeleton::GetCallingUid();
2634         auto appRecord = GetAppRunningRecordByAbilityToken(token);
2635         if (!appRecord || appRecord->GetUid() != callerUid) {
2636             HILOG_ERROR("Permission verification failed.");
2637             return ERR_PERMISSION_DENIED;
2638         }
2639     } else {
2640         HILOG_ERROR("Permission verification failed.");
2641         return ERR_PERMISSION_DENIED;
2642     }
2643 
2644     return ERR_OK;
2645 }
2646 
VerifyAPL() const2647 bool AppMgrServiceInner::VerifyAPL() const
2648 {
2649     if (!appRunningManager_) {
2650         HILOG_ERROR("appRunningManager_ is nullptr");
2651         return false;
2652     }
2653 
2654     auto callerPid = IPCSkeleton::GetCallingPid();
2655     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
2656     if (!appRecord) {
2657         HILOG_ERROR("Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
2658         return false;
2659     }
2660 
2661     auto applicationInfo = appRecord->GetApplicationInfo();
2662     if (!applicationInfo) {
2663         HILOG_ERROR("Get application info failed.");
2664         return false;
2665     }
2666 
2667     auto apl = applicationInfo->appPrivilegeLevel;
2668     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
2669         HILOG_ERROR("caller is not system_basic or system_core.");
2670         return false;
2671     }
2672     return true;
2673 }
2674 
VerifyAccountPermission(const std::string & permissionName,const int userId) const2675 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId) const
2676 {
2677     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2678     if (isSaCall) {
2679         return ERR_OK;
2680     }
2681 
2682     if (userId != currentUserId_) {
2683         auto isCallingPermAccount = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2684             AAFwk::PermissionConstants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
2685         if (!isCallingPermAccount) {
2686             HILOG_ERROR("%{public}s: Permission accounts verification failed", __func__);
2687             return ERR_PERMISSION_DENIED;
2688         }
2689     }
2690     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(permissionName);
2691     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
2692 }
2693 
VerifyRequestPermission() const2694 int AppMgrServiceInner::VerifyRequestPermission() const
2695 {
2696     auto callerUid = IPCSkeleton::GetCallingUid();
2697 
2698     if (callerUid == ROOT_UID || callerUid == FOUNDATION_UID) {
2699         return ERR_OK;
2700     } else {
2701         HILOG_ERROR("Permission verification failed.[DongLin]%{public}d", callerUid);
2702         return ERR_PERMISSION_DENIED;
2703     }
2704 }
2705 
PreStartNWebSpawnProcess(const pid_t hostPid)2706 int AppMgrServiceInner::PreStartNWebSpawnProcess(const pid_t hostPid)
2707 {
2708     HILOG_INFO("AppMgrServiceInner::PreStartNWebSpawnProcess");
2709     if (hostPid <= 0) {
2710         HILOG_ERROR("invalid param, hostPid:%{public}d", hostPid);
2711         return ERR_INVALID_VALUE;
2712     }
2713 
2714     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
2715     if (!nwebSpawnClient) {
2716         HILOG_ERROR("nwebSpawnClient is null");
2717         return ERR_INVALID_VALUE;
2718     }
2719 
2720     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(hostPid);
2721     if (!appRecord) {
2722         HILOG_ERROR("no such app Record, pid:%{public}d", hostPid);
2723         return ERR_INVALID_VALUE;
2724     }
2725 
2726     ErrCode errCode = nwebSpawnClient->PreStartNWebSpawnProcess();
2727     if (FAILED(errCode)) {
2728         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
2729         return ERR_INVALID_VALUE;
2730     }
2731 
2732     return 0;
2733 }
2734 
StartRenderProcess(const pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,pid_t & renderPid)2735 int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam,
2736     int32_t ipcFd, int32_t sharedFd, pid_t &renderPid)
2737 {
2738     HILOG_INFO("start render process, hostPid:%{public}d", hostPid);
2739     if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0) {
2740         HILOG_ERROR("invalid param: hostPid:%{public}d renderParam:%{private}s ipcFd:%{public}d sharedFd:%{public}d",
2741             hostPid, renderParam.c_str(), ipcFd, sharedFd);
2742         return ERR_INVALID_VALUE;
2743     }
2744 
2745     if (!appRunningManager_) {
2746         HILOG_ERROR("appRunningManager_ is nullptr, not start render process");
2747         return ERR_INVALID_VALUE;
2748     }
2749 
2750     auto appRecord = GetAppRunningRecordByPid(hostPid);
2751     if (!appRecord) {
2752         HILOG_ERROR("no such appRecord, hostPid:%{public}d", hostPid);
2753         return ERR_INVALID_VALUE;
2754     }
2755 
2756     auto renderRecord = appRecord->GetRenderRecord();
2757     if (renderRecord) {
2758         HILOG_WARN("already exit render process,do not request again, renderPid:%{public}d", renderRecord->GetPid());
2759         renderPid = renderRecord->GetPid();
2760         return ERR_ALREADY_EXIST_RENDER;
2761     }
2762 
2763     renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam, ipcFd, sharedFd, appRecord);
2764     if (!renderRecord) {
2765         HILOG_ERROR("create render record failed, hostPid:%{public}d", hostPid);
2766         return ERR_INVALID_VALUE;
2767     }
2768 
2769     return StartRenderProcessImpl(renderRecord, appRecord, renderPid);
2770 }
2771 
AttachRenderProcess(const pid_t pid,const sptr<IRenderScheduler> & scheduler)2772 void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler)
2773 {
2774     HILOG_DEBUG("attach render process start");
2775     if (pid <= 0) {
2776         HILOG_ERROR("invalid render process pid:%{public}d", pid);
2777         return;
2778     }
2779     if (!scheduler) {
2780         HILOG_ERROR("render scheduler is null");
2781         return;
2782     }
2783 
2784     if (!appRunningManager_) {
2785         HILOG_ERROR("appRunningManager_ is null");
2786         return;
2787     }
2788 
2789     HILOG_INFO("attach render process pid:%{public}d", pid);
2790     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
2791     if (!appRecord) {
2792         HILOG_ERROR("no such app Record, pid:%{public}d", pid);
2793         return;
2794     }
2795 
2796     auto renderRecord = appRecord->GetRenderRecord();
2797     if (!renderRecord) {
2798         HILOG_ERROR("no such render Record, pid:%{public}d", pid);
2799         return;
2800     }
2801 
2802     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
2803     appDeathRecipient->SetEventHandler(eventHandler_);
2804     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
2805     appDeathRecipient->SetIsRenderProcess(true);
2806     renderRecord->SetScheduler(scheduler);
2807     renderRecord->SetDeathRecipient(appDeathRecipient);
2808     renderRecord->RegisterDeathRecipient();
2809 
2810     // notify fd to render process
2811     scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(), renderRecord->GetSharedFd());
2812 }
2813 
StartRenderProcessImpl(const std::shared_ptr<RenderRecord> & renderRecord,const std::shared_ptr<AppRunningRecord> appRecord,pid_t & renderPid)2814 int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
2815     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid)
2816 {
2817     if (!renderRecord || !appRecord) {
2818         HILOG_ERROR("renderRecord or appRecord is nullptr.");
2819         return ERR_INVALID_VALUE;
2820     }
2821 
2822     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
2823     if (!nwebSpawnClient) {
2824         HILOG_ERROR("nwebSpawnClient is null");
2825         return ERR_INVALID_VALUE;
2826     }
2827 
2828     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
2829     startMsg.renderParam = renderRecord->GetRenderParam();
2830     startMsg.code = 0; // 0: DEFAULT
2831     pid_t pid = 0;
2832     ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid);
2833     if (FAILED(errCode)) {
2834         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
2835         return ERR_INVALID_VALUE;
2836     }
2837     renderPid = pid;
2838     appRecord->SetRenderRecord(renderRecord);
2839     renderRecord->SetPid(pid);
2840     HILOG_INFO("start render process success, hostPid:%{public}d, pid:%{public}d uid:%{public}d",
2841         renderRecord->GetHostPid(), pid, startMsg.uid);
2842     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessCreated(renderRecord);
2843     return 0;
2844 }
2845 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)2846 int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
2847 {
2848     if (remoteClientManager_ == nullptr) {
2849         HILOG_ERROR("remoteClientManager_ is null");
2850         return ERR_INVALID_VALUE;
2851     }
2852     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
2853     if (!nwebSpawnClient) {
2854         HILOG_ERROR("nwebSpawnClient is null");
2855         return ERR_INVALID_VALUE;
2856     }
2857 
2858     AppSpawnStartMsg startMsg;
2859     startMsg.pid = renderPid;
2860     startMsg.code = 1; // 1: GET_RENDER_TERMINATION_STATUS
2861     ErrCode errCode = nwebSpawnClient->GetRenderProcessTerminationStatus(startMsg, status);
2862     if (FAILED(errCode)) {
2863         HILOG_ERROR("failed to get render process termination status, errCode %{public}08x", errCode);
2864         return ERR_INVALID_VALUE;
2865     }
2866     HILOG_INFO("Get render process termination status success, renderPid:%{public}d, status:%{public}d",
2867         renderPid, status);
2868     return 0;
2869 }
2870 
OnRenderRemoteDied(const wptr<IRemoteObject> & remote)2871 void AppMgrServiceInner::OnRenderRemoteDied(const wptr<IRemoteObject> &remote)
2872 {
2873     HILOG_ERROR("On render remote died.");
2874     if (appRunningManager_) {
2875         auto renderRecord = appRunningManager_->OnRemoteRenderDied(remote);
2876         if (renderRecord) {
2877             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
2878         }
2879     }
2880 }
2881 
BuildStartFlags(const AAFwk::Want & want,const AbilityInfo & abilityInfo)2882 uint32_t AppMgrServiceInner::BuildStartFlags(const AAFwk::Want &want, const AbilityInfo &abilityInfo)
2883 {
2884     uint32_t startFlags = 0x0;
2885     if (want.GetBoolParam("coldStart", false)) {
2886         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::COLD_START);
2887     }
2888 
2889     if (want.GetIntParam(DLP_PARAMS_INDEX, 0) != 0) {
2890         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DLP_MANAGER);
2891     }
2892 
2893     if (abilityInfo.extensionAbilityType == ExtensionAbilityType::BACKUP) {
2894         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::BACKUP_EXTENSION);
2895     }
2896 
2897     if (abilityInfo.applicationInfo.debug) {
2898         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
2899     }
2900     if (abilityInfo.applicationInfo.asanEnabled) {
2901 	    startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::ASANENABLED);
2902     }
2903 
2904     return startFlags;
2905 }
2906 
AddWatchParameter()2907 void AppMgrServiceInner::AddWatchParameter()
2908 {
2909     HILOG_INFO("%{public}s called.", __func__);
2910     auto context = new (std::nothrow) std::weak_ptr<AppMgrServiceInner>(shared_from_this());
2911     int ret = WatchParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, PointerDeviceEventCallback,
2912         context);
2913     if (ret != 0) {
2914         HILOG_ERROR("watch parameter %{public}s failed with %{public}d.",
2915             AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, ret);
2916     }
2917 }
2918 
InitFocusListener()2919 void AppMgrServiceInner::InitFocusListener()
2920 {
2921     HILOG_INFO("begin initFocus listener.");
2922     if (focusListener_) {
2923         return;
2924     }
2925 
2926     focusListener_ = new WindowFocusChangedListener(shared_from_this(), eventHandler_);
2927     auto registerTask = [innerService = shared_from_this()]() {
2928         if (innerService) {
2929             HILOG_INFO("RegisterFocusListener task");
2930             innerService->RegisterFocusListener();
2931         }
2932     };
2933     if (eventHandler_) {
2934         eventHandler_->PostTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
2935     }
2936 }
2937 
RegisterFocusListener()2938 void AppMgrServiceInner::RegisterFocusListener()
2939 {
2940     HILOG_INFO("RegisterFocusListener begin");
2941     if (!focusListener_) {
2942         HILOG_ERROR("no focusListener_");
2943         return;
2944     }
2945     WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
2946     HILOG_INFO("RegisterFocusListener end");
2947 }
2948 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)2949 void AppMgrServiceInner::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
2950 {
2951     if (!focusChangeInfo) {
2952         HILOG_WARN("focused, invalid focusChangeInfo");
2953         return;
2954     }
2955     HILOG_DEBUG("focused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
2956 
2957     if (focusChangeInfo->pid_ <= 0) {
2958         HILOG_ERROR("invalid pid:%{public}d", focusChangeInfo->pid_);
2959         return;
2960     }
2961 
2962     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
2963     if (!appRecord) {
2964         HILOG_ERROR("focused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
2965         return;
2966     }
2967 
2968     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, true)) {
2969         HILOG_DEBUG("only change ability focus state, do not change process or application focus state.");
2970         return;
2971     }
2972 
2973     bool needNotifyApp = appRunningManager_->IsApplicationFirstFocused(*appRecord);
2974     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp);
2975     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
2976 }
2977 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)2978 void AppMgrServiceInner::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
2979 {
2980     if (!focusChangeInfo) {
2981         HILOG_WARN("unfocused, invalid focusChangeInfo");
2982         return;
2983     }
2984     HILOG_DEBUG("unfocused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
2985 
2986     if (focusChangeInfo->pid_ <= 0) {
2987         HILOG_ERROR("invalid pid:%{public}d", focusChangeInfo->pid_);
2988         return;
2989     }
2990 
2991     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
2992     if (!appRecord) {
2993         HILOG_ERROR("unfocused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
2994         return;
2995     }
2996 
2997     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, false)) {
2998         HILOG_DEBUG("only change ability from focus to unfocus, do not change process or application focus state.");
2999         return;
3000     }
3001 
3002     bool needNotifyApp = appRunningManager_->IsApplicationUnfocused(appRecord->GetBundleName());
3003     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp);
3004     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
3005 }
3006 
PointerDeviceEventCallback(const char * key,const char * value,void * context)3007 void AppMgrServiceInner::PointerDeviceEventCallback(const char *key, const char *value, void *context)
3008 {
3009     HILOG_INFO("%{public}s called.", __func__);
3010     auto weak = static_cast<std::weak_ptr<AppMgrServiceInner>*>(context);
3011     if (weak == nullptr) {
3012         HILOG_ERROR("context is nullptr.");
3013         return;
3014     }
3015 
3016     auto appMgrServiceInner = weak->lock();
3017     if (appMgrServiceInner == nullptr) {
3018         HILOG_ERROR("app manager service inner is nullptr.");
3019         return;
3020     }
3021 
3022     if ((strcmp(key, AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE) != 0) ||
3023         ((strcmp(value, "true") != 0) && (strcmp(value, "false") != 0))) {
3024         HILOG_ERROR("key %{public}s or value %{public}s mismatch.", key, value);
3025         return;
3026     }
3027 
3028     Configuration changeConfig;
3029     if (!changeConfig.AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, value)) {
3030         HILOG_ERROR("add %{public}s item to configuration failed.", key);
3031         return;
3032     }
3033 
3034     HILOG_DEBUG("update config %{public}s to %{public}s", key, value);
3035     auto result = appMgrServiceInner->UpdateConfiguration(changeConfig);
3036     if (result != 0) {
3037         HILOG_ERROR("update config failed with %{public}d, key: %{public}s, value: %{public}s.", result, key, value);
3038         return;
3039     }
3040 }
3041 
GetAppRunningStateByBundleName(const std::string & bundleName)3042 bool AppMgrServiceInner::GetAppRunningStateByBundleName(const std::string &bundleName)
3043 {
3044     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3045     HILOG_DEBUG("function called.");
3046     if (!appRunningManager_) {
3047         HILOG_ERROR("app running manager is nullptr.");
3048         return false;
3049     }
3050 
3051     return appRunningManager_->GetAppRunningStateByBundleName(bundleName);
3052 }
3053 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)3054 int32_t AppMgrServiceInner::NotifyLoadRepairPatch(const std::string &bundleName,
3055     const sptr<IQuickFixCallback> &callback)
3056 {
3057     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3058     HILOG_DEBUG("function called.");
3059     if (!appRunningManager_) {
3060         HILOG_ERROR("app running manager is nullptr.");
3061         return ERR_INVALID_OPERATION;
3062     }
3063 
3064     return appRunningManager_->NotifyLoadRepairPatch(bundleName, callback);
3065 }
3066 
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)3067 int32_t AppMgrServiceInner::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
3068 {
3069     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3070     HILOG_DEBUG("function called.");
3071     if (!appRunningManager_) {
3072         HILOG_ERROR("app running manager is nullptr.");
3073         return ERR_INVALID_OPERATION;
3074     }
3075 
3076     return appRunningManager_->NotifyHotReloadPage(bundleName, callback);
3077 }
3078 
3079 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
SetContinuousTaskProcess(int32_t pid,bool isContinuousTask)3080 int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask)
3081 {
3082     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
3083     if (!isSaCall) {
3084         HILOG_ERROR("callerToken not SA %{public}s", __func__);
3085         return ERR_INVALID_VALUE;
3086     }
3087 
3088     if (!appRunningManager_) {
3089         HILOG_ERROR("app running manager is nullptr.");
3090         return ERR_INVALID_OPERATION;
3091     }
3092 
3093     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(pid);
3094     if (!appRecord) {
3095         HILOG_ERROR("Get app running record by pid failed. pid: %{public}d", pid);
3096         return false;
3097     }
3098     appRecord->SetContinuousTaskAppState(isContinuousTask);
3099     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
3100 
3101     return ERR_OK;
3102 }
3103 #endif
3104 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)3105 int32_t AppMgrServiceInner::NotifyUnLoadRepairPatch(const std::string &bundleName,
3106     const sptr<IQuickFixCallback> &callback)
3107 {
3108     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3109     HILOG_DEBUG("function called.");
3110     if (!appRunningManager_) {
3111         HILOG_ERROR("app running manager is nullptr.");
3112         return ERR_INVALID_OPERATION;
3113     }
3114 
3115     return appRunningManager_->NotifyUnLoadRepairPatch(bundleName, callback);
3116 }
3117 
SetCurrentUserId(const int32_t userId)3118 void AppMgrServiceInner::SetCurrentUserId(const int32_t userId)
3119 {
3120     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
3121         return;
3122     }
3123     HILOG_DEBUG("set current userId: %{public}d", userId);
3124     currentUserId_ = userId;
3125 }
3126 }  // namespace AppExecFwk
3127 }  // namespace OHOS
3128