• 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     if (!isSaCall) {
802         HILOG_ERROR("callerToken not SA %{public}s", __func__);
803         return ERR_INVALID_VALUE;
804     }
805     if (!(level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_MODERATE ||
806         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_CRITICAL ||
807         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_LOW)) {
808         HILOG_ERROR("Level value error!");
809         return ERR_INVALID_VALUE;
810     }
811     if (!appRunningManager_) {
812         HILOG_ERROR("appRunningManager nullptr!");
813         return ERR_INVALID_VALUE;
814     }
815 
816     return appRunningManager_->NotifyMemoryLevel(level);
817 }
818 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)819 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
820     std::vector<RunningProcessInfo> &info)
821 {
822     RunningProcessInfo runningProcessInfo;
823     GetRunningProcess(appRecord, runningProcessInfo);
824     info.emplace_back(runningProcessInfo);
825 }
826 
GetRunningProcess(const std::shared_ptr<AppRunningRecord> & appRecord,RunningProcessInfo & info)827 void AppMgrServiceInner::GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
828     RunningProcessInfo &info)
829 {
830     info.processName_ = appRecord->GetProcessName();
831     info.pid_ = appRecord->GetPriorityObject()->GetPid();
832     info.uid_ = appRecord->GetUid();
833     info.state_ = static_cast<AppProcessState>(appRecord->GetState());
834     info.isContinuousTask = appRecord->IsContinuousTask();
835     info.isKeepAlive = appRecord->IsKeepAliveApp();
836     info.isFocused = appRecord->GetFocusFlag();
837     info.startTimeMillis_ = appRecord->GetAppStartTime();
838     appRecord->GetBundleNames(info.bundleNames);
839 }
840 
KillProcessByPid(const pid_t pid) const841 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid) const
842 {
843     int32_t ret = -1;
844     if (pid > 0) {
845         HILOG_INFO("kill pid %{public}d", pid);
846         ret = kill(pid, SIGNAL_KILL);
847     }
848     AAFwk::EventInfo eventInfo;
849     auto appRecord = GetAppRunningRecordByPid(pid);
850     if (!appRecord) {
851         return ret;
852     }
853     auto applicationInfo = appRecord->GetApplicationInfo();
854     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
855     eventInfo.bundleName = applicationInfo->name;
856     eventInfo.versionName = applicationInfo->versionName;
857     eventInfo.versionCode = applicationInfo->versionCode;
858     eventInfo.processName = appRecord->GetProcessName();
859     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
860     return ret;
861 }
862 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)863 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
864 {
865     int64_t delayTime = SystemTimeMillisecond() - startTime;
866     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
867         if (CheckAllProcessExist(pids)) {
868             return true;
869         }
870         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
871         delayTime = SystemTimeMillisecond() - startTime;
872     }
873     return false;
874 }
875 
GetAllPids(std::list<pid_t> & pids)876 bool AppMgrServiceInner::GetAllPids(std::list<pid_t> &pids)
877 {
878     for (const auto &appTaskInfo : appProcessManager_->GetRecentAppList()) {
879         if (appTaskInfo) {
880             auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
881             if (appRecord) {
882                 pids.push_back(appTaskInfo->GetPid());
883                 appRecord->ScheduleProcessSecurityExit();
884             }
885         }
886     }
887     return (pids.empty() ? false : true);
888 }
889 
ProcessExist(pid_t & pid)890 bool AppMgrServiceInner::ProcessExist(pid_t &pid)
891 {
892     char pid_path[128] = {0};
893     struct stat stat_buf;
894     if (!pid) {
895         return false;
896     }
897     if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) {
898         return false;
899     }
900     if (stat(pid_path, &stat_buf) == 0) {
901         return true;
902     }
903     return false;
904 }
905 
CheckAllProcessExist(std::list<pid_t> & pids)906 bool AppMgrServiceInner::CheckAllProcessExist(std::list<pid_t> &pids)
907 {
908     for (auto iter = pids.begin(); iter != pids.end();) {
909         if (!ProcessExist(*iter)) {
910             iter = pids.erase(iter);
911         } else {
912             iter++;
913         }
914     }
915     if (pids.empty()) {
916         return true;
917     }
918     return false;
919 }
920 
SystemTimeMillisecond()921 int64_t AppMgrServiceInner::SystemTimeMillisecond()
922 {
923     struct timespec t;
924     t.tv_sec = 0;
925     t.tv_nsec = 0;
926     clock_gettime(CLOCK_MONOTONIC, &t);
927     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
928 }
929 
GetAppRunningRecordByPid(const pid_t pid) const930 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
931 {
932     if (!appRunningManager_) {
933         HILOG_ERROR("appRunningManager nullptr!");
934         return nullptr;
935     }
936     return appRunningManager_->GetAppRunningRecordByPid(pid);
937 }
938 
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)939 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(const sptr<IRemoteObject> &token,
940     const sptr<IRemoteObject> &preToken, const std::shared_ptr<ApplicationInfo> &appInfo,
941     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
942     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
943 {
944     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
945     if (!appRunningManager_) {
946         HILOG_ERROR("appRunningManager nullptr!");
947         return nullptr;
948     }
949     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
950     if (!appRecord) {
951         HILOG_ERROR("get app record failed");
952         return nullptr;
953     }
954 
955     bool isKeepAlive = bundleInfo.isKeepAlive && bundleInfo.singleton;
956     appRecord->SetKeepAliveAppState(isKeepAlive, false);
957     appRecord->SetEventHandler(eventHandler_);
958     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
959     if (want) {
960         appRecord->SetDebugApp(want->GetBoolParam("debugApp", false));
961         if (want->GetBoolParam(COLD_START, false)) {
962             appRecord->SetDebugApp(true);
963         }
964         appRecord->SetAppIndex(want->GetIntParam(DLP_PARAMS_INDEX, 0));
965         appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
966         appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0));
967     }
968 
969     if (preToken) {
970         auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
971         if (abilityRecord) {
972             abilityRecord->SetPreToken(preToken);
973         }
974     }
975 
976     return appRecord;
977 }
978 
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag)979 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag)
980 {
981     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
982     HILOG_DEBUG("Terminate ability come.");
983     if (!token) {
984         HILOG_ERROR("AppMgrServiceInner::TerminateAbility token is null!");
985         return;
986     }
987     auto appRecord = GetAppRunningRecordByAbilityToken(token);
988     if (!appRecord) {
989         HILOG_ERROR("AppMgrServiceInner::TerminateAbility app is not exist!");
990         return;
991     }
992 
993     if (appRunningManager_) {
994         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner = shared_from_this();
995         appRunningManager_->TerminateAbility(token, clearMissionFlag, appMgrServiceInner);
996     }
997 }
998 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)999 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
1000 {
1001     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1002     HILOG_INFO("AppMgrService start to update the ability to state %{public}d.", static_cast<int32_t>(state));
1003     if (!token) {
1004         HILOG_ERROR("token is null!");
1005         return;
1006     }
1007 
1008     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1009     if (!appRecord) {
1010         HILOG_ERROR("app is not exist!");
1011         return;
1012     }
1013     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1014     if (!abilityRecord) {
1015         HILOG_ERROR("can not find ability record!");
1016         return;
1017     }
1018     if (state == abilityRecord->GetState()) {
1019         HILOG_ERROR("current state is already, no need update!");
1020         return;
1021     }
1022     if (abilityRecord->GetAbilityInfo() == nullptr) {
1023         HILOG_ERROR("ability info nullptr!");
1024         return;
1025     }
1026     auto type = abilityRecord->GetAbilityInfo()->type;
1027     if (type == AppExecFwk::AbilityType::SERVICE &&
1028         (state == AbilityState::ABILITY_STATE_CREATE ||
1029         state == AbilityState::ABILITY_STATE_TERMINATED ||
1030         state == AbilityState::ABILITY_STATE_CONNECTED ||
1031         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
1032         HILOG_INFO("StateChangedNotifyObserver service type, state:%{public}d", static_cast<int32_t>(state));
1033         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true);
1034         return;
1035     }
1036     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
1037         HILOG_ERROR("state is not foreground or background!");
1038         return;
1039     }
1040 
1041     appRecord->UpdateAbilityState(token, state);
1042 }
1043 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)1044 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
1045 {
1046     if (!token) {
1047         HILOG_ERROR("token is null!");
1048         return;
1049     }
1050     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1051     if (!appRecord) {
1052         HILOG_ERROR("app is not exist!");
1053         return;
1054     }
1055     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1056     if (!abilityRecord) {
1057         HILOG_ERROR("can not find ability record!");
1058         return;
1059     }
1060     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false);
1061 }
1062 
OnStop()1063 void AppMgrServiceInner::OnStop()
1064 {
1065     if (!appRunningManager_) {
1066         HILOG_ERROR("appRunningManager nullptr!");
1067         return;
1068     }
1069 
1070     appRunningManager_->ClearAppRunningRecordMap();
1071     CloseAppSpawnConnection();
1072 }
1073 
OpenAppSpawnConnection()1074 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
1075 {
1076     if (remoteClientManager_ == nullptr) {
1077         HILOG_ERROR("remoteClientManager_ is null");
1078         return ERR_INVALID_VALUE;
1079     }
1080 
1081     if (remoteClientManager_->GetSpawnClient()) {
1082         return remoteClientManager_->GetSpawnClient()->OpenConnection();
1083     }
1084     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
1085 }
1086 
CloseAppSpawnConnection() const1087 void AppMgrServiceInner::CloseAppSpawnConnection() const
1088 {
1089     if (remoteClientManager_ == nullptr) {
1090         HILOG_ERROR("remoteClientManager_ is null");
1091         return;
1092     }
1093 
1094     if (remoteClientManager_->GetSpawnClient()) {
1095         remoteClientManager_->GetSpawnClient()->CloseConnection();
1096     }
1097 }
1098 
QueryAppSpawnConnectionState() const1099 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
1100 {
1101     if (remoteClientManager_ == nullptr) {
1102         HILOG_ERROR("remoteClientManager_ is null");
1103         return SpawnConnectionState::STATE_NOT_CONNECT;
1104     }
1105 
1106     if (remoteClientManager_->GetSpawnClient()) {
1107         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
1108     }
1109     return SpawnConnectionState::STATE_NOT_CONNECT;
1110 }
1111 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)1112 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
1113 {
1114     if (remoteClientManager_ == nullptr) {
1115         HILOG_ERROR("remoteClientManager_ is null");
1116         return;
1117     }
1118 
1119     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
1120 }
1121 
SetBundleManager(sptr<IBundleMgr> bundleManager)1122 void AppMgrServiceInner::SetBundleManager(sptr<IBundleMgr> bundleManager)
1123 {
1124     if (remoteClientManager_ == nullptr) {
1125         HILOG_ERROR("remoteClientManager_ is null");
1126         return;
1127     }
1128 
1129     remoteClientManager_->SetBundleManager(bundleManager);
1130 }
1131 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)1132 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
1133 {
1134     pid_t callingPid = IPCSkeleton::GetCallingPid();
1135     pid_t pid = getpid();
1136     if (callingPid != pid) {
1137         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
1138         return;
1139     }
1140     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1141     if (callback != nullptr) {
1142         appStateCallbacks_.push_back(callback);
1143     }
1144 }
1145 
AbilityBehaviorAnalysis(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const int32_t visibility,const int32_t perceptibility,const int32_t connectionState)1146 void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1147     const int32_t visibility,       // 0:false,1:true
1148     const int32_t perceptibility,   // 0:false,1:true
1149     const int32_t connectionState)  // 0:false,1:true
1150 {
1151     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1152     if (!token) {
1153         HILOG_ERROR("token is null");
1154         return;
1155     }
1156     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1157     if (!appRecord) {
1158         HILOG_ERROR("app record is not exist for ability token");
1159         return;
1160     }
1161     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
1162     if (!abilityRecord) {
1163         HILOG_ERROR("ability record is not exist for ability previous token");
1164         return;
1165     }
1166     if (preToken) {
1167         abilityRecord->SetPreToken(preToken);
1168     }
1169     abilityRecord->SetVisibility(visibility);
1170     abilityRecord->SetPerceptibility(perceptibility);
1171     abilityRecord->SetConnectionState(connectionState);
1172 }
1173 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)1174 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
1175 {
1176     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1177     if (!token) {
1178         HILOG_ERROR("token is null");
1179         return;
1180     }
1181     auto appRecord = GetAppRunningRecordByAbilityToken(token);
1182     if (!appRecord) {
1183         HILOG_ERROR("app record is not exist for ability token");
1184         return;
1185     }
1186 
1187     // before exec ScheduleProcessSecurityExit return
1188     // The resident process won't let him die
1189     if (appRecord->IsKeepAliveApp()) {
1190         return;
1191     }
1192 
1193     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1194     if (pid > 0) {
1195         std::list<pid_t> pids;
1196         pids.push_back(pid);
1197         appRecord->ScheduleProcessSecurityExit();
1198         if (!WaitForRemoteProcessExit(pids, SystemTimeMillisecond())) {
1199             int32_t result = KillProcessByPid(pid);
1200             if (result < 0) {
1201                 HILOG_ERROR("KillProcessByAbilityToken kill process is fail");
1202                 return;
1203             }
1204         }
1205     }
1206 }
1207 
KillProcessesByUserId(int32_t userId)1208 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId)
1209 {
1210     if (!appRunningManager_) {
1211         HILOG_ERROR("appRunningManager_ is nullptr");
1212         return;
1213     }
1214 
1215     int64_t startTime = SystemTimeMillisecond();
1216     std::list<pid_t> pids;
1217     if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
1218         HILOG_INFO("The process corresponding to the userId did not start");
1219         return;
1220     }
1221     if (WaitForRemoteProcessExit(pids, startTime)) {
1222         HILOG_INFO("The remote process exited successfully ");
1223         return;
1224     }
1225     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1226         auto result = KillProcessByPid(*iter);
1227         if (result < 0) {
1228             HILOG_ERROR("KillProcessByPid is failed. pid: %{public}d", *iter);
1229             return;
1230         }
1231     }
1232 }
1233 
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)1234 void AppMgrServiceInner::StartAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
1235     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<AppRunningRecord> &appRecord,
1236     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1237 {
1238     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1239     HILOG_INFO("already create appRecord, just start ability");
1240     if (!appRecord) {
1241         HILOG_ERROR("appRecord is null");
1242         return;
1243     }
1244 
1245     if (want) {
1246         want->SetParam(DLP_PARAMS_SECURITY_FLAG, appRecord->GetSecurityFlag());
1247     }
1248 
1249     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
1250     if (abilityInfo->launchMode == LaunchMode::SINGLETON && ability != nullptr) {
1251         HILOG_WARN("same ability info in singleton launch mode, will not add ability");
1252         return;
1253     }
1254 
1255     if (ability && preToken) {
1256         HILOG_ERROR("Ability is already started");
1257         ability->SetPreToken(preToken);
1258         return;
1259     }
1260 
1261     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
1262     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1263     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
1264     if (!moduleRecord) {
1265         HILOG_ERROR("add moduleRecord failed");
1266         return;
1267     }
1268 
1269     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
1270     if (!ability) {
1271         HILOG_ERROR("add ability failed");
1272         return;
1273     }
1274 
1275     if (preToken != nullptr) {
1276         ability->SetPreToken(preToken);
1277     }
1278 
1279     ApplicationState appState = appRecord->GetState();
1280     if (appState == ApplicationState::APP_STATE_CREATE) {
1281         HILOG_ERROR("in create state, don't launch ability");
1282         return;
1283     }
1284     appRecord->LaunchAbility(ability);
1285 }
1286 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const1287 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
1288     const sptr<IRemoteObject> &abilityToken) const
1289 {
1290     if (!appRunningManager_) {
1291         HILOG_ERROR("appRunningManager_ is nullptr");
1292         return nullptr;
1293     }
1294 
1295     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
1296 }
1297 
AbilityTerminated(const sptr<IRemoteObject> & token)1298 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
1299 {
1300     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1301     HILOG_DEBUG("Terminate ability come.");
1302     if (!token) {
1303         HILOG_ERROR("Terminate ability error, token is null!");
1304         return;
1305     }
1306 
1307     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
1308     if (!appRecord) {
1309         HILOG_ERROR("Terminate ability error, appRecord is not exist!");
1310         return;
1311     }
1312 
1313     appRecord->AbilityTerminated(token);
1314 }
1315 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const1316 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
1317 {
1318     if (appRunningManager_ == nullptr) {
1319         HILOG_ERROR("appRunningManager is nullptr");
1320         return nullptr;
1321     }
1322     const auto&& appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
1323     const auto& iter = appRunningRecordMap.find(recordId);
1324     return iter != appRunningRecordMap.end() ? iter->second : nullptr;
1325 }
1326 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp)1327 void AppMgrServiceInner::OnAppStateChanged(
1328     const std::shared_ptr<AppRunningRecord> &appRecord, const ApplicationState state, bool needNotifyApp)
1329 {
1330     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1331     if (!appRecord) {
1332         HILOG_ERROR("OnAppStateChanged come, app record is null");
1333         return;
1334     }
1335 
1336     HILOG_DEBUG("OnAppStateChanged begin, bundleName is %{public}s, state:%{public}d",
1337         appRecord->GetBundleName().c_str(), static_cast<int32_t>(state));
1338     for (const auto &callback : appStateCallbacks_) {
1339         if (callback != nullptr) {
1340             callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
1341         }
1342     }
1343 
1344     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStateChanged(appRecord, state, needNotifyApp);
1345 }
1346 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1347 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
1348     const ApplicationState state)
1349 {
1350     AppProcessData processData;
1351     auto appInfoList = appRecord->GetAppInfoList();
1352     for (const auto &list : appInfoList) {
1353         AppData data;
1354         data.appName = list->name;
1355         data.uid = list->uid;
1356         processData.appDatas.push_back(data);
1357     }
1358     processData.processName = appRecord->GetProcessName();
1359     processData.pid = appRecord->GetPriorityObject()->GetPid();
1360     processData.appState = state;
1361     processData.isFocused = appRecord->GetFocusFlag();
1362     return processData;
1363 }
1364 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)1365 void AppMgrServiceInner::OnAbilityStateChanged(
1366     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
1367 {
1368     if (!ability) {
1369         HILOG_ERROR("ability is null");
1370         return;
1371     }
1372     for (const auto &callback : appStateCallbacks_) {
1373         if (callback != nullptr) {
1374             callback->OnAbilityRequestDone(ability->GetToken(), state);
1375         }
1376     }
1377 }
1378 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility)1379 void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility)
1380 {
1381     DelayedSingleton<AppStateObserverManager>::GetInstance()->StateChangedNotifyObserver(abilityStateData, isAbility);
1382 }
1383 
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)1384 void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, uint32_t startFlags,
1385                                       const std::shared_ptr<AppRunningRecord> &appRecord, const int uid,
1386                                       const std::string &bundleName, const int32_t bundleIndex)
1387 {
1388     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1389     if (!remoteClientManager_->GetSpawnClient() || !appRecord) {
1390         HILOG_ERROR("appSpawnClient or appRecord is null");
1391         return;
1392     }
1393 
1394     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
1395     if (bundleMgr_ == nullptr) {
1396         HILOG_ERROR("GetBundleManager fail");
1397         return;
1398     }
1399 
1400     auto userId = GetUserIdByUid(uid);
1401     BundleInfo bundleInfo;
1402     bool bundleMgrResult;
1403     if (bundleIndex == 0) {
1404         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetBundleInfo");
1405         bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfo(bundleName,
1406             BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION, bundleInfo, userId));
1407     } else {
1408         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetSandboxBundleInfo");
1409         bundleMgrResult = (IN_PROCESS_CALL(bundleMgr_->GetSandboxBundleInfo(bundleName,
1410             bundleIndex, userId, bundleInfo)) == 0);
1411     }
1412 
1413     if (!bundleMgrResult) {
1414         HILOG_ERROR("GetBundleInfo is fail");
1415         return;
1416     }
1417 
1418     bool hasAccessBundleDirReq = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
1419         [] (const auto &reqPermission) {
1420             if (PERMISSION_ACCESS_BUNDLE_DIR == reqPermission) {
1421                 return true;
1422             }
1423 
1424             return false;
1425         });
1426     uint8_t setAllowInternet = 0;
1427     uint8_t allowInternet = 1;
1428     auto token = bundleInfo.applicationInfo.accessTokenId;
1429     {
1430         // Add TRACE
1431         HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::VerifyAccessToken");
1432         int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_INTERNET);
1433         if (result != Security::AccessToken::PERMISSION_GRANTED) {
1434             setAllowInternet = 1;
1435             allowInternet = 0;
1436         }
1437 
1438         if (hasAccessBundleDirReq) {
1439             int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_ACCESS_BUNDLE_DIR);
1440             if (result != Security::AccessToken::PERMISSION_GRANTED) {
1441                 HILOG_ERROR("StartProcess PERMISSION_ACCESS_BUNDLE_DIR NOT GRANTED");
1442                 hasAccessBundleDirReq = false;
1443             }
1444         }
1445     }
1446 
1447     AppSpawnStartMsg startMsg;
1448     startMsg.uid = bundleInfo.uid;
1449     startMsg.gid = bundleInfo.gid;
1450     startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId;
1451     startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel;
1452     startMsg.bundleName = bundleName;
1453     startMsg.renderParam = RENDER_PARAM;
1454     startMsg.flags = startFlags;
1455     startMsg.bundleIndex = bundleIndex;
1456     startMsg.setAllowInternet = setAllowInternet;
1457     startMsg.allowInternet = allowInternet;
1458     if (hasAccessBundleDirReq) {
1459         startMsg.flags = startMsg.flags | APP_ACCESS_BUNDLE_DIR;
1460     }
1461 
1462     HILOG_DEBUG("Start process, apl is %{public}s, bundleName is %{public}s, startFlags is %{public}d.",
1463         startMsg.apl.c_str(), bundleName.c_str(), startFlags);
1464 
1465     bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleGidsByUid(bundleName, uid, startMsg.gids));
1466     if (!bundleMgrResult) {
1467         HILOG_ERROR("GetBundleGids is fail");
1468         return;
1469     }
1470 
1471     startMsg.procName = processName;
1472     startMsg.soPath = SO_PATH;
1473 
1474     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
1475     pid_t pid = 0;
1476     ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
1477     if (FAILED(errCode)) {
1478         HILOG_ERROR("failed to spawn new app process, errCode %{public}08x", errCode);
1479         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1480         return;
1481     }
1482     HILOG_INFO("Start process success, pid is %{public}d, processName is %{public}s.", pid, processName.c_str());
1483     appRecord->GetPriorityObject()->SetPid(pid);
1484     appRecord->SetUid(startMsg.uid);
1485     appRecord->SetStartMsg(startMsg);
1486     appRecord->SetAppMgrServiceInner(weak_from_this());
1487     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false);
1488     AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
1489     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessCreated(appRecord);
1490     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
1491 }
1492 
RemoveAppFromRecentList(const std::string & appName,const std::string & processName)1493 void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, const std::string &processName)
1494 {
1495     int64_t startTime = 0;
1496     std::list<pid_t> pids;
1497     auto appTaskInfo = appProcessManager_->GetAppTaskInfoByProcessName(appName, processName);
1498     if (!appTaskInfo) {
1499         return;
1500     }
1501     auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
1502     if (!appRecord) {
1503         appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
1504         return;
1505     }
1506 
1507     // Do not delete resident processes, before exec ScheduleProcessSecurityExit
1508     if (appRecord->IsKeepAliveApp()) {
1509         return;
1510     }
1511 
1512     startTime = SystemTimeMillisecond();
1513     pids.push_back(appTaskInfo->GetPid());
1514     appRecord->ScheduleProcessSecurityExit();
1515     if (!WaitForRemoteProcessExit(pids, startTime)) {
1516         int32_t result = KillProcessByPid(appTaskInfo->GetPid());
1517         if (result < 0) {
1518             HILOG_ERROR("RemoveAppFromRecentList kill process is fail");
1519             return;
1520         }
1521     }
1522     appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
1523 }
1524 
GetRecentAppList() const1525 const std::list<const std::shared_ptr<AppTaskInfo>> &AppMgrServiceInner::GetRecentAppList() const
1526 {
1527     return appProcessManager_->GetRecentAppList();
1528 }
1529 
ClearRecentAppList()1530 void AppMgrServiceInner::ClearRecentAppList()
1531 {
1532     int64_t startTime = 0;
1533     std::list<pid_t> pids;
1534     if (GetAllPids(pids)) {
1535         return;
1536     }
1537 
1538     startTime = SystemTimeMillisecond();
1539     if (WaitForRemoteProcessExit(pids, startTime)) {
1540         appProcessManager_->ClearRecentAppList();
1541         return;
1542     }
1543     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1544         int32_t result = KillProcessByPid(*iter);
1545         if (result < 0) {
1546             HILOG_ERROR("ClearRecentAppList kill process is fail");
1547             return;
1548         }
1549     }
1550     appProcessManager_->ClearRecentAppList();
1551 }
1552 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess)1553 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess)
1554 {
1555     HILOG_ERROR("On remote died.");
1556     if (isRenderProcess) {
1557         OnRenderRemoteDied(remote);
1558         return;
1559     }
1560 
1561     auto appRecord = appRunningManager_->OnRemoteDied(remote);
1562     if (!appRecord) {
1563         return;
1564     }
1565 
1566     ClearAppRunningData(appRecord, false);
1567 }
1568 
ClearAppRunningData(const std::shared_ptr<AppRunningRecord> & appRecord,bool containsApp)1569 void AppMgrServiceInner::ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord, bool containsApp)
1570 {
1571     if (!appRecord) {
1572         return;
1573     }
1574 
1575     if (containsApp) {
1576         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1577     }
1578 
1579     FinishUserTestLocked("App died", -1, appRecord);
1580     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_REMOTE_DIED);
1581 
1582     for (const auto &item : appRecord->GetAbilities()) {
1583         const auto &abilityRecord = item.second;
1584         appRecord->StateChangedNotifyObserver(abilityRecord,
1585             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true);
1586     }
1587     RemoveAppFromRecentListById(appRecord->GetRecordId());
1588     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
1589 
1590     // kill render if exist.
1591     auto renderRecord = appRecord->GetRenderRecord();
1592     if (renderRecord && renderRecord->GetPid() > 0) {
1593         HILOG_DEBUG("Kill render process when host died.");
1594         KillProcessByPid(renderRecord->GetPid());
1595         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
1596     }
1597 
1598     if (appRecord->IsKeepAliveApp()) {
1599         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
1600             innerService->RestartResidentProcess(appRecord);
1601         };
1602         if (appRecord->CanRestartResidentProc()) {
1603             if (!eventHandler_) {
1604                 HILOG_ERROR("eventHandler_ is nullptr");
1605                 return;
1606             }
1607             eventHandler_->PostTask(restartProcess, "RestartResidentProcess");
1608         } else {
1609             auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
1610                 return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
1611             };
1612             auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(),
1613                 findRestartResidentTask);
1614             if (findIter != restartResedentTaskList_.end()) {
1615                 HILOG_WARN("The restart app task has been registered.");
1616                 return;
1617             }
1618             restartResedentTaskList_.emplace_back(appRecord);
1619             HILOG_INFO("PostRestartResidentProcessDelayTask.");
1620             eventHandler_->PostTask(restartProcess, "RestartResidentProcessDelayTask", RESTART_INTERVAL_TIME);
1621         }
1622     }
1623 }
1624 
PushAppFront(const int32_t recordId)1625 void AppMgrServiceInner::PushAppFront(const int32_t recordId)
1626 {
1627     appProcessManager_->PushAppFront(recordId);
1628 }
1629 
RemoveAppFromRecentListById(const int32_t recordId)1630 void AppMgrServiceInner::RemoveAppFromRecentListById(const int32_t recordId)
1631 {
1632     appProcessManager_->RemoveAppFromRecentListById(recordId);
1633 }
1634 
AddAppToRecentList(const std::string & appName,const std::string & processName,const pid_t pid,const int32_t recordId)1635 void AppMgrServiceInner::AddAppToRecentList(
1636     const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId)
1637 {
1638     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1639     appProcessManager_->AddAppToRecentList(appName, processName, pid, recordId);
1640 }
1641 
GetAppTaskInfoById(const int32_t recordId) const1642 const std::shared_ptr<AppTaskInfo> AppMgrServiceInner::GetAppTaskInfoById(const int32_t recordId) const
1643 {
1644     return appProcessManager_->GetAppTaskInfoById(recordId);
1645 }
1646 
AddAppDeathRecipient(const pid_t pid,const sptr<AppDeathRecipient> & appDeathRecipient) const1647 void AppMgrServiceInner::AddAppDeathRecipient(const pid_t pid, const sptr<AppDeathRecipient> &appDeathRecipient) const
1648 {
1649     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1650     std::shared_ptr<AppRunningRecord> appRecord = GetAppRunningRecordByPid(pid);
1651     if (appRecord) {
1652         appRecord->SetAppDeathRecipient(appDeathRecipient);
1653     }
1654 }
1655 
HandleTimeOut(const InnerEvent::Pointer & event)1656 void AppMgrServiceInner::HandleTimeOut(const InnerEvent::Pointer &event)
1657 {
1658     HILOG_INFO("handle time out");
1659     if (!appRunningManager_ || event == nullptr) {
1660         HILOG_ERROR("appRunningManager or event is nullptr");
1661         return;
1662     }
1663 
1664     // check libc.hook_mode
1665     const int bufferLen = 128;
1666     char paramOutBuf[bufferLen] = {0};
1667     const char *hook_mode = "startup:";
1668     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
1669     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
1670         HILOG_DEBUG("HandleTimeOut, Hook_mode: no handle time out");
1671         return;
1672     }
1673 
1674     switch (event->GetInnerEventId()) {
1675         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
1676             appRunningManager_->HandleTerminateTimeOut(event->GetParam());
1677             break;
1678         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
1679             SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1680             HandleTerminateApplicationTimeOut(event->GetParam());
1681             break;
1682         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
1683         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
1684             SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1685             HandleAddAbilityStageTimeOut(event->GetParam());
1686             break;
1687         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
1688             SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1689             HandleStartSpecifiedAbilityTimeOut(event->GetParam());
1690             break;
1691         default:
1692             break;
1693     }
1694 }
1695 
SetEventHandler(const std::shared_ptr<AMSEventHandler> & handler)1696 void AppMgrServiceInner::SetEventHandler(const std::shared_ptr<AMSEventHandler> &handler)
1697 {
1698     eventHandler_ = handler;
1699 }
1700 
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)1701 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
1702 {
1703     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1704     HILOG_INFO("%{public}s called", __func__);
1705     if (!appRunningManager_) {
1706         HILOG_ERROR("appRunningManager_ is nullptr");
1707         return;
1708     }
1709     appRunningManager_->HandleAbilityAttachTimeOut(token);
1710 }
1711 
PrepareTerminate(const sptr<IRemoteObject> & token)1712 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token)
1713 {
1714     HILOG_INFO("AppMgrService prepare to terminate the ability.");
1715     if (!appRunningManager_) {
1716         HILOG_ERROR("appRunningManager_ is nullptr");
1717         return;
1718     }
1719     appRunningManager_->PrepareTerminate(token);
1720 }
1721 
HandleTerminateApplicationTimeOut(const int64_t eventId)1722 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId)
1723 {
1724     HILOG_INFO("handle terminate application time out");
1725     if (!appRunningManager_) {
1726         HILOG_ERROR("appRunningManager_ is nullptr");
1727         return;
1728     }
1729     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
1730     TerminateApplication(appRecord);
1731 }
1732 
TerminateApplication(const std::shared_ptr<AppRunningRecord> & appRecord)1733 void AppMgrServiceInner::TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
1734 {
1735     if (!appRecord) {
1736         HILOG_ERROR("appRecord is nullptr");
1737         return;
1738     }
1739     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
1740     appRecord->RemoveAppDeathRecipient();
1741     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT);
1742     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false);
1743     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1744     if (pid > 0) {
1745         auto timeoutTask = [pid, innerService = shared_from_this()]() {
1746             HILOG_INFO("KillProcessByPid %{public}d", pid);
1747             int32_t result = innerService->KillProcessByPid(pid);
1748             if (result < 0) {
1749                 HILOG_ERROR("KillProcessByPid kill process is fail");
1750                 return;
1751             }
1752         };
1753         if (!eventHandler_) {
1754             HILOG_ERROR("eventHandler_ is nullptr");
1755             return;
1756         }
1757         eventHandler_->PostTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
1758     }
1759     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1760     RemoveAppFromRecentListById(appRecord->GetRecordId());
1761     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
1762 }
1763 
HandleAddAbilityStageTimeOut(const int64_t eventId)1764 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId)
1765 {
1766     HILOG_INFO("called add ability stage info time out!");
1767     if (!appRunningManager_) {
1768         HILOG_ERROR("appRunningManager_ is nullptr");
1769         return;
1770     }
1771     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
1772     if (!appRecord) {
1773         HILOG_ERROR("appRecord is nullptr");
1774         return;
1775     }
1776 
1777     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
1778         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
1779     }
1780 
1781     KillApplicationByRecord(appRecord);
1782 }
1783 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)1784 void AppMgrServiceInner::GetRunningProcessInfoByToken(
1785     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
1786 {
1787     HILOG_INFO("%{public}s called", __func__);
1788     if (!CheckGetRunningInfoPermission()) {
1789         return;
1790     }
1791 
1792     appRunningManager_->GetRunningProcessInfoByToken(token, info);
1793 }
1794 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info) const1795 void AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info) const
1796 {
1797     HILOG_INFO("%{public}s called", __func__);
1798     if (!CheckGetRunningInfoPermission()) {
1799         return;
1800     }
1801 
1802     appRunningManager_->GetRunningProcessInfoByPid(pid, info);
1803 }
1804 
CheckGetRunningInfoPermission() const1805 bool AppMgrServiceInner::CheckGetRunningInfoPermission() const
1806 {
1807     if (!appRunningManager_) {
1808         HILOG_ERROR("appRunningManager_ is nullptr");
1809         return false;
1810     }
1811 
1812     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1813     if (!isPerm) {
1814         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1815         return false;
1816     }
1817 
1818     return true;
1819 }
1820 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)1821 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
1822 {
1823     HILOG_INFO("%{public}s called", __func__);
1824 
1825     HILOG_INFO("bundle info size: [%{public}zu]", infos.size());
1826     StartResidentProcess(infos, -1, true);
1827 }
1828 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount,bool isEmptyKeepAliveApp)1829 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount,
1830     bool isEmptyKeepAliveApp)
1831 {
1832     HILOG_INFO("start resident process");
1833     if (infos.empty()) {
1834         HILOG_ERROR("infos is empty!");
1835         return;
1836     }
1837 
1838     if (!appRunningManager_) {
1839         HILOG_ERROR("appRunningManager_ is nullptr");
1840         return;
1841     }
1842 
1843     for (auto &bundle : infos) {
1844         HILOG_INFO("processName = [%{public}s]", bundle.applicationInfo.process.c_str());
1845         if (bundle.applicationInfo.process.empty()) {
1846             continue;
1847         }
1848         auto processName = bundle.applicationInfo.process;
1849         // Inspection records
1850         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
1851             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
1852         if (appRecord) {
1853             HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
1854             continue;
1855         }
1856         HILOG_INFO("Start empty resident process, processName = [%{public}s]", processName.c_str());
1857         StartEmptyResidentProcess(bundle, processName, restartCount, isEmptyKeepAliveApp);
1858     }
1859 }
1860 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount,bool isEmptyKeepAliveApp)1861 void AppMgrServiceInner::StartEmptyResidentProcess(
1862     const BundleInfo &info, const std::string &processName, int restartCount, bool isEmptyKeepAliveApp)
1863 {
1864     HILOG_INFO("start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
1865     if (!CheckRemoteClient() || !appRunningManager_) {
1866         HILOG_INFO("Failed to start resident process!");
1867         return;
1868     }
1869 
1870     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
1871     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
1872     if (!appRecord) {
1873         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
1874         return;
1875     }
1876 
1877     StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, appInfo->bundleName, 0);
1878 
1879     // If it is empty, the startup failed
1880     if (!appRecord) {
1881         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
1882         return;
1883     }
1884 
1885     appRecord->SetKeepAliveAppState(true, isEmptyKeepAliveApp);
1886 
1887     if (restartCount > 0) {
1888         HILOG_INFO("StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount);
1889         appRecord->SetRestartResidentProcCount(restartCount);
1890     }
1891 
1892     appRecord->SetEventHandler(eventHandler_);
1893     appRecord->AddModules(appInfo, info.hapModuleInfos);
1894     HILOG_INFO("StartEmptyResidentProcess of pid : [%{public}d], ", appRecord->GetPriorityObject()->GetPid());
1895 }
1896 
CheckRemoteClient()1897 bool AppMgrServiceInner::CheckRemoteClient()
1898 {
1899     if (!remoteClientManager_) {
1900         HILOG_ERROR("remoteClientManager_ is null");
1901         return false;
1902     }
1903 
1904     if (!remoteClientManager_->GetSpawnClient()) {
1905         HILOG_ERROR("appSpawnClient is null");
1906         return false;
1907     }
1908 
1909     if (!remoteClientManager_->GetBundleManager()) {
1910         HILOG_ERROR("GetBundleManager fail");
1911         return false;
1912     }
1913     return true;
1914 }
1915 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)1916 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
1917 {
1918     if (appRecord == nullptr) {
1919         HILOG_ERROR("Restart resident process failed, the appRecord is nullptr.");
1920         return;
1921     }
1922     struct timespec t;
1923     t.tv_sec = 0;
1924     t.tv_nsec = 0;
1925     clock_gettime(CLOCK_MONOTONIC, &t);
1926     appRecord->SetRestartTimeMillis(static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS));
1927     appRecord->DecRestartResidentProcCount();
1928 
1929     auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
1930         return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
1931     };
1932     auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(), findRestartResidentTask);
1933     if (findIter != restartResedentTaskList_.end()) {
1934         restartResedentTaskList_.erase(findIter);
1935     }
1936 
1937     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
1938         HILOG_ERROR("restart resident process failed!");
1939         return;
1940     }
1941 
1942     auto bundleMgr = remoteClientManager_->GetBundleManager();
1943     BundleInfo bundleInfo;
1944     auto callerUid = IPCSkeleton::GetCallingUid();
1945     auto userId = GetUserIdByUid(callerUid);
1946     if (!IN_PROCESS_CALL(
1947         bundleMgr->GetBundleInfo(appRecord->GetBundleName(), BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
1948         HILOG_ERROR("GetBundleInfo fail");
1949         return;
1950     }
1951     std::vector<BundleInfo> infos;
1952     infos.emplace_back(bundleInfo);
1953     HILOG_INFO("the resident process [%{public}s] remaining restarts num is [%{public}d]",
1954         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
1955     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount(), appRecord->IsEmptyKeepAliveApp());
1956 }
1957 
NotifyAppStatus(const std::string & bundleName,const std::string & eventData)1958 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData)
1959 {
1960     HILOG_INFO("%{public}s called, bundle name is %{public}s, event is %{public}s",
1961         __func__, bundleName.c_str(), eventData.c_str());
1962     Want want;
1963     want.SetAction(eventData);
1964     ElementName element;
1965     element.SetBundleName(bundleName);
1966     want.SetElement(element);
1967     want.SetParam(Constants::USER_ID, 0);
1968     EventFwk::CommonEventData commonData {want};
1969     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1970 }
1971 
NotifyAppStatusByCallerUid(const std::string & bundleName,const int32_t userId,const int32_t callerUid,const std::string & eventData)1972 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t userId,
1973     const int32_t callerUid, const std::string &eventData)
1974 {
1975     HILOG_INFO("%{public}s called, bundle name is %{public}s, , userId is %{public}d, event is %{public}s",
1976         __func__, bundleName.c_str(), userId, eventData.c_str());
1977     Want want;
1978     want.SetAction(eventData);
1979     ElementName element;
1980     element.SetBundleName(bundleName);
1981     want.SetElement(element);
1982     want.SetParam(Constants::USER_ID, userId);
1983     want.SetParam(Constants::UID, callerUid);
1984     EventFwk::CommonEventData commonData {want};
1985     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1986 }
1987 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)1988 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(
1989     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
1990 {
1991     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterApplicationStateObserver(
1992         observer, bundleNameList);
1993 }
1994 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)1995 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
1996 {
1997     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterApplicationStateObserver(observer);
1998 }
1999 
GetForegroundApplications(std::vector<AppStateData> & list)2000 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
2001 {
2002     HILOG_INFO("%{public}s, begin.", __func__);
2003     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2004     if (!isPerm) {
2005         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2006         return ERR_PERMISSION_DENIED;
2007     }
2008 
2009     appRunningManager_->GetForegroundApplications(list);
2010     return ERR_OK;
2011 }
2012 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)2013 int AppMgrServiceInner::StartUserTestProcess(
2014     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
2015 {
2016     HILOG_INFO("Enter");
2017     if (!observer) {
2018         HILOG_ERROR("observer nullptr.");
2019         return ERR_INVALID_VALUE;
2020     }
2021     if (!appRunningManager_) {
2022         HILOG_ERROR("appRunningManager_ is nullptr");
2023         return ERR_INVALID_VALUE;
2024     }
2025 
2026     std::string bundleName = want.GetStringParam("-b");
2027     if (bundleName.empty()) {
2028         HILOG_ERROR("Invalid bundle name");
2029         return ERR_INVALID_VALUE;
2030     }
2031 
2032     if (KillApplicationByUserIdLocked(bundleName, userId)) {
2033         HILOG_ERROR("Failed to kill the application");
2034         return ERR_INVALID_VALUE;
2035     }
2036 
2037     HapModuleInfo hapModuleInfo;
2038     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
2039         HILOG_ERROR("Failed to get HapModuleInfo for TestRunner");
2040         return ERR_INVALID_VALUE;
2041     }
2042 
2043     std::string processName;
2044     MakeProcessName(std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo, processName);
2045     HILOG_INFO("processName = [%{public}s]", processName.c_str());
2046 
2047     // Inspection records
2048     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
2049         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
2050     if (appRecord) {
2051         HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
2052         return ERR_INVALID_VALUE;
2053     }
2054 
2055     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
2056 }
2057 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)2058 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2059     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
2060 {
2061     HILOG_INFO("Enter");
2062     if (!observer) {
2063         HILOG_ERROR("observer nullptr.");
2064         return ERR_INVALID_VALUE;
2065     }
2066 
2067     bool moduleJson = false;
2068     if (!bundleInfo.hapModuleInfos.empty()) {
2069         moduleJson = bundleInfo.hapModuleInfos.back().isModuleJson;
2070     }
2071     if (moduleJson) {
2072         std::string moduleName = want.GetStringParam("-m");
2073         if (moduleName.empty()) {
2074             UserTestAbnormalFinish(observer, "No module name is specified.");
2075             return ERR_INVALID_VALUE;
2076         }
2077 
2078         bool found = false;
2079         for (auto item : bundleInfo.hapModuleInfos) {
2080             if (item.moduleName == moduleName) {
2081                 hapModuleInfo = item;
2082                 found = true;
2083                 break;
2084             }
2085         }
2086         if (!found) {
2087             UserTestAbnormalFinish(observer, "The specified module name is not found.");
2088             return ERR_INVALID_VALUE;
2089         }
2090     }
2091     return ERR_OK;
2092 }
2093 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)2094 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
2095 {
2096     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
2097     if (!observerProxy) {
2098         HILOG_ERROR("Failed to get ITestObserver proxy");
2099         return ERR_INVALID_VALUE;
2100     }
2101     observerProxy->TestFinished(msg, -1);
2102     return ERR_OK;
2103 }
2104 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)2105 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
2106     const BundleInfo &info, const std::string &processName, const int userId)
2107 {
2108     HILOG_INFO("enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
2109     if (!CheckRemoteClient() || !appRunningManager_) {
2110         HILOG_ERROR("Failed to start the process being tested!");
2111         return ERR_INVALID_VALUE;
2112     }
2113 
2114     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
2115     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
2116     if (!appRecord) {
2117         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
2118         return ERR_INVALID_VALUE;
2119     }
2120 
2121     auto isDebug = want.GetBoolParam("debugApp", false);
2122     HILOG_INFO("Set Debug : %{public}s", (isDebug ? "true" : "false"));
2123     appRecord->SetDebugApp(isDebug);
2124     if (want.GetBoolParam(COLD_START, false)) {
2125         appRecord->SetDebugApp(true);
2126     }
2127 
2128     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
2129     if (!testRecord) {
2130         HILOG_ERROR("Failed to make UserTestRecord!");
2131         return ERR_INVALID_VALUE;
2132     }
2133     testRecord->want = want;
2134     testRecord->observer = observer;
2135     testRecord->isFinished = false;
2136     testRecord->userId = userId;
2137     appRecord->SetUserTestInfo(testRecord);
2138 
2139     int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2140     uint32_t startFlags = 0x0;
2141     if (info.applicationInfo.debug) {
2142         startFlags = startFlags | (AppSpawn::ClientSocket::APPSPAWN_COLD_BOOT << StartFlags::DEBUGGABLE);
2143     }
2144     StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, appInfo->bundleName, bundleIndex);
2145 
2146     // If it is empty, the startup failed
2147     if (!appRecord) {
2148         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
2149         return ERR_INVALID_VALUE;
2150     }
2151 
2152     appRecord->SetEventHandler(eventHandler_);
2153     appRecord->AddModules(appInfo, info.hapModuleInfos);
2154     HILOG_INFO("StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid());
2155 
2156     return ERR_OK;
2157 }
2158 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName,const pid_t & pid)2159 int AppMgrServiceInner::FinishUserTest(
2160     const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid)
2161 {
2162     HILOG_INFO("Enter");
2163     if (bundleName.empty()) {
2164         HILOG_ERROR("Invalid bundle name.");
2165         return ERR_INVALID_VALUE;
2166     }
2167     auto appRecord = GetAppRunningRecordByPid(pid);
2168     if (!appRecord) {
2169         HILOG_ERROR("no such appRecord");
2170         return ERR_INVALID_VALUE;
2171     }
2172 
2173     auto userTestRecord = appRecord->GetUserTestInfo();
2174     if (!userTestRecord) {
2175         HILOG_ERROR("unstart user test");
2176         return ERR_INVALID_VALUE;
2177     }
2178 
2179     FinishUserTestLocked(msg, resultCode, appRecord);
2180 
2181     int ret = KillApplicationByUserIdLocked(bundleName, userTestRecord->userId);
2182     if (ret) {
2183         HILOG_ERROR("Failed to kill process.");
2184         return ret;
2185     }
2186 
2187     return ERR_OK;
2188 }
2189 
FinishUserTestLocked(const std::string & msg,const int64_t & resultCode,const std::shared_ptr<AppRunningRecord> & appRecord)2190 int AppMgrServiceInner::FinishUserTestLocked(
2191     const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord)
2192 {
2193     HILOG_INFO("Enter");
2194     if (!appRecord) {
2195         HILOG_ERROR("Invalid appRecord");
2196         return ERR_INVALID_VALUE;
2197     }
2198 
2199     std::unique_lock<std::mutex> lock(userTestLock_);
2200     auto userTestRecord = appRecord->GetUserTestInfo();
2201     if (!userTestRecord) {
2202         HILOG_WARN("not start user test");
2203         return ERR_INVALID_VALUE;
2204     }
2205     if (!userTestRecord->isFinished) {
2206         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
2207         if (!observerProxy) {
2208             HILOG_ERROR("Failed to get ITestObserver proxy");
2209             return ERR_INVALID_VALUE;
2210         }
2211         observerProxy->TestFinished(msg, resultCode);
2212 
2213         userTestRecord->isFinished = true;
2214     }
2215 
2216     return ERR_OK;
2217 }
2218 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo)2219 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)
2220 {
2221     HILOG_DEBUG("Start specified ability.");
2222     if (!CheckRemoteClient()) {
2223         return;
2224     }
2225 
2226     BundleInfo bundleInfo;
2227     HapModuleInfo hapModuleInfo;
2228     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
2229 
2230     int32_t appIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2231     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
2232         return;
2233     }
2234 
2235     std::string processName;
2236     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
2237     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, processName);
2238 
2239     std::vector<HapModuleInfo> hapModules;
2240     hapModules.emplace_back(hapModuleInfo);
2241 
2242     std::shared_ptr<AppRunningRecord> appRecord;
2243     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
2244     if (!appRecord) {
2245         // new app record
2246         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
2247         if (!appRecord) {
2248             HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2249             return;
2250         }
2251         appRecord->SetEventHandler(eventHandler_);
2252         appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
2253             AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT);
2254         uint32_t startFlags = BuildStartFlags(want, abilityInfo);
2255         int32_t bundleIndex = want.GetIntParam(DLP_PARAMS_INDEX, 0);
2256         StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, appInfo->bundleName,
2257             bundleIndex);
2258 
2259         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2260         appRecord->AddModules(appInfo, hapModules);
2261     } else {
2262         HILOG_DEBUG("process is exist");
2263         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2264         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
2265         if (!moduleRecord) {
2266             HILOG_DEBUG("module record is nullptr, add modules");
2267             appRecord->AddModules(appInfo, hapModules);
2268             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
2269         } else {
2270             HILOG_DEBUG("schedule accept want");
2271             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
2272         }
2273     }
2274 }
2275 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)2276 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
2277 {
2278     if (!response) {
2279         HILOG_ERROR("response is nullptr, register failed.");
2280         return;
2281     }
2282 
2283     pid_t callingPid = IPCSkeleton::GetCallingPid();
2284     pid_t pid = getpid();
2285     if (callingPid != pid) {
2286         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
2287         return;
2288     }
2289 
2290     startSpecifiedAbilityResponse_ = response;
2291 }
2292 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)2293 void AppMgrServiceInner::ScheduleAcceptWantDone(
2294     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
2295 {
2296     HILOG_DEBUG("Schedule accept want done, flag: %{public}s", flag.c_str());
2297 
2298     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
2299     if (!appRecord) {
2300         HILOG_ERROR("Get app record failed.");
2301         return;
2302     }
2303     appRecord->ScheduleAcceptWantDone();
2304 
2305     if (startSpecifiedAbilityResponse_) {
2306         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag);
2307     }
2308 }
2309 
HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)2310 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)
2311 {
2312     HILOG_DEBUG("called start specified ability time out!");
2313     if (!appRunningManager_) {
2314         HILOG_ERROR("appRunningManager_ is nullptr");
2315         return;
2316     }
2317 
2318     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2319     if (!appRecord) {
2320         HILOG_ERROR("appRecord is nullptr");
2321         return;
2322     }
2323 
2324     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
2325         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
2326     }
2327 
2328     KillApplicationByRecord(appRecord);
2329 }
2330 
UpdateConfiguration(const Configuration & config)2331 int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config)
2332 {
2333     if (!appRunningManager_) {
2334         HILOG_ERROR("appRunningManager_ is null");
2335         return ERR_INVALID_VALUE;
2336     }
2337 
2338     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
2339     if (ret != ERR_OK) {
2340         return ret;
2341     }
2342 
2343     std::vector<std::string> changeKeyV;
2344     configuration_->CompareDifferent(changeKeyV, config);
2345     HILOG_INFO("changeKeyV size :%{public}zu", changeKeyV.size());
2346     if (changeKeyV.empty()) {
2347         HILOG_ERROR("changeKeyV is empty");
2348         return ERR_INVALID_VALUE;
2349     }
2350     configuration_->Merge(changeKeyV, config);
2351     // all app
2352     int32_t result = appRunningManager_->UpdateConfiguration(config);
2353     if (result != ERR_OK) {
2354         HILOG_ERROR("update error, not notify");
2355         return result;
2356     }
2357     // notify
2358     std::lock_guard<std::recursive_mutex> notifyLock(configurationObserverLock_);
2359     for (auto &observer : configurationObservers_) {
2360         if (observer != nullptr) {
2361             observer->OnConfigurationUpdated(config);
2362         }
2363     }
2364     return result;
2365 }
2366 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)2367 int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
2368 {
2369     HILOG_INFO("AppMgrServiceInner::RegisterConfigurationObserver: called");
2370 
2371     if (observer == nullptr) {
2372         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
2373         return ERR_INVALID_VALUE;
2374     }
2375     std::lock_guard<std::recursive_mutex> registerLock(configurationObserverLock_);
2376     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
2377         [&observer](const sptr<IConfigurationObserver> &item) {
2378             return (item && item->AsObject() == observer->AsObject());
2379         }
2380     );
2381     if (it != configurationObservers_.end()) {
2382         HILOG_ERROR("AppMgrServiceInner::Register error: observer exist");
2383         return ERR_INVALID_VALUE;
2384     }
2385     configurationObservers_.push_back(observer);
2386     return NO_ERROR;
2387 }
2388 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)2389 int32_t AppMgrServiceInner::UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
2390 {
2391     HILOG_INFO("AppMgrServiceInner::UnregisterConfigurationObserver: called");
2392     if (observer == nullptr) {
2393         HILOG_ERROR("AppMgrServiceInner::Register error: observer is null");
2394         return ERR_INVALID_VALUE;
2395     }
2396     std::lock_guard<std::recursive_mutex> unregisterLock(configurationObserverLock_);
2397     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
2398         [&observer](const sptr<IConfigurationObserver> &item) {
2399             return (item && item->AsObject() == observer->AsObject());
2400         }
2401     );
2402     if (it != configurationObservers_.end()) {
2403         configurationObservers_.erase(it);
2404         return NO_ERROR;
2405     }
2406     HILOG_INFO("AppMgrServiceInner ConfigurationObserver not register");
2407     return ERR_INVALID_VALUE;
2408 }
2409 
InitGlobalConfiguration()2410 void AppMgrServiceInner::InitGlobalConfiguration()
2411 {
2412     if (!configuration_) {
2413         HILOG_ERROR("configuration_ is null");
2414         return;
2415     }
2416 
2417 #ifdef SUPPORT_GRAPHICS
2418     // Currently only this interface is known
2419     auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
2420     HILOG_INFO("current global language is : %{public}s", language.c_str());
2421     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
2422 #endif
2423 
2424     // Assign to default colorMode "light"
2425     HILOG_INFO("current global colorMode is : %{public}s", ConfigurationInner::COLOR_MODE_LIGHT);
2426     configuration_->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
2427 
2428     // Get input pointer device
2429     std::string hasPointerDevice = system::GetParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "false");
2430     HILOG_INFO("current hasPointerDevice is %{public}s", hasPointerDevice.c_str());
2431     configuration_->AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, hasPointerDevice);
2432 
2433     // Get DeviceType
2434     auto deviceType = GetDeviceType();
2435     HILOG_INFO("current deviceType is %{public}s", deviceType);
2436     configuration_->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType);
2437 }
2438 
GetConfiguration()2439 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
2440 {
2441     return configuration_;
2442 }
2443 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)2444 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
2445 {
2446     HILOG_DEBUG("Kill application by appRecord.");
2447     if (!appRecord || !eventHandler_) {
2448         HILOG_WARN("appRecord or eventHandler_ is nullptr.");
2449         return;
2450     }
2451 
2452     auto pid = appRecord->GetPriorityObject()->GetPid();
2453     appRecord->SetTerminating();
2454     appRecord->ScheduleProcessSecurityExit();
2455 
2456     auto startTime = SystemTimeMillisecond();
2457     std::list<pid_t> pids = {pid};
2458     if (WaitForRemoteProcessExit(pids, startTime)) {
2459         HILOG_INFO("The remote process exited successfully");
2460         return;
2461     }
2462 
2463     auto timeoutTask = [pid, innerService = shared_from_this()]() {
2464         HILOG_INFO("KillProcessByPid %{public}d", pid);
2465         int32_t result = innerService->KillProcessByPid(pid);
2466         if (result < 0) {
2467             HILOG_ERROR("Kill application by app record failed, pid: %{public}d", pid);
2468             return;
2469         }
2470     };
2471     eventHandler_->PostTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
2472 }
2473 
SendHiSysEvent(const int32_t innerEventId,const int64_t eventId)2474 void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_t eventId)
2475 {
2476     HILOG_DEBUG("called AppMgrServiceInner SendHiSysEvent!");
2477     if (!appRunningManager_) {
2478         HILOG_ERROR("appRunningManager_ is nullptr");
2479         return;
2480     }
2481 
2482     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2483     if (!appRecord) {
2484         HILOG_ERROR("appRecord is nullptr");
2485         return;
2486     }
2487     const int bufferLen = 128;
2488     char paramOutBuf[bufferLen] = {0};
2489     const char *hook_mode = "startup:";
2490     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
2491     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
2492         HILOG_DEBUG("SendHiSysEvent, Hook_mode: no handle time out");
2493         return;
2494     }
2495 
2496     std::string eventName = EVENT_NAME_LIFECYCLE_TIMEOUT;
2497     int32_t pid = appRecord->GetPriorityObject()->GetPid();
2498     int32_t uid = appRecord->GetUid();
2499     std::string packageName = appRecord->GetBundleName();
2500     std::string processName = appRecord->GetProcessName();
2501     std::string msg;
2502     switch (innerEventId) {
2503         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
2504             msg = EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
2505             break;
2506         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
2507             msg = EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
2508             break;
2509         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
2510             msg = EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
2511             break;
2512         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
2513             msg = EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
2514             break;
2515         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
2516             msg = EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
2517             break;
2518         default:
2519             msg = EVENT_MESSAGE_DEFAULT;
2520             break;
2521     }
2522 
2523     HILOG_DEBUG("SendHiSysEvent, eventName = %{public}s, uid = %{public}d, pid = %{public}d, \
2524         packageName = %{public}s, processName = %{public}s, msg = %{public}s",
2525         eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
2526 
2527     OHOS::HiviewDFX::HiSysEvent::Write(
2528         OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK,
2529         eventName,
2530         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
2531         EVENT_KEY_PID, pid,
2532         EVENT_KEY_UID, uid,
2533         EVENT_KEY_PACKAGE_NAME, packageName,
2534         EVENT_KEY_PROCESS_NAME, processName,
2535         EVENT_KEY_MESSAGE, msg);
2536 }
2537 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)2538 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
2539 {
2540     auto appRecord = GetAppRunningRecordByPid(pid);
2541     if (!appRecord) {
2542         HILOG_ERROR("no such appRecord");
2543         return ERR_NAME_NOT_FOUND;
2544     }
2545 
2546     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2547     auto callingPid = IPCSkeleton::GetCallingPid();
2548     if (!isSaCall && callingPid != pid) {
2549         HILOG_ERROR("Permission verify failed.");
2550         return ERR_PERMISSION_DENIED;
2551     }
2552     for (auto &item : appRecord->GetAbilities()) {
2553         tokens.emplace_back(item.first);
2554     }
2555     return ERR_OK;
2556 }
2557 
GetApplicationInfoByProcessID(const int pid,AppExecFwk::ApplicationInfo & application,bool & debug)2558 int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application,
2559     bool &debug)
2560 {
2561     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2562     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
2563     if (!isSaCall && !isShellCall) {
2564         HILOG_ERROR("no permissions.");
2565         return ERR_PERMISSION_DENIED;
2566     }
2567     auto appRecord = GetAppRunningRecordByPid(pid);
2568     if (!appRecord) {
2569         HILOG_ERROR("no such appRecord for PID:%{public}d", pid);
2570         return ERR_NAME_NOT_FOUND;
2571     }
2572 
2573     auto info = appRecord->GetApplicationInfo();
2574     if (info == nullptr) {
2575         HILOG_ERROR("ApplicationInfo is nullptr !");
2576         return ERR_NO_INIT;
2577     }
2578     application = *info;
2579     debug = appRecord->IsDebugApp();
2580     return ERR_OK;
2581 }
2582 
VerifyProcessPermission(const std::string & bundleName) const2583 int AppMgrServiceInner::VerifyProcessPermission(const std::string &bundleName) const
2584 {
2585     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2586     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
2587     if (isSaCall || isShellCall) {
2588         return ERR_OK;
2589     }
2590 
2591     if (VerifyAPL()) {
2592         return ERR_OK;
2593     }
2594 
2595     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2596         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
2597     if (isCallingPerm) {
2598         if (AAFwk::PermissionVerification::GetInstance()->IsGatewayCall()) {
2599             return ERR_OK;
2600         }
2601         auto callerPid = IPCSkeleton::GetCallingPid();
2602         auto appRecord = GetAppRunningRecordByPid(callerPid);
2603         if (!appRecord || appRecord->GetBundleName() != bundleName) {
2604             HILOG_ERROR("Permission verification failed.");
2605             return ERR_PERMISSION_DENIED;
2606         }
2607     } else {
2608         HILOG_ERROR("Permission verification failed.");
2609         return ERR_PERMISSION_DENIED;
2610     }
2611 
2612     return ERR_OK;
2613 }
2614 
VerifyProcessPermission(const sptr<IRemoteObject> & token) const2615 int AppMgrServiceInner::VerifyProcessPermission(const sptr<IRemoteObject> &token) const
2616 {
2617     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2618     if (isSaCall) {
2619         return ERR_OK;
2620     }
2621 
2622     if (VerifyAPL()) {
2623         return ERR_OK;
2624     }
2625 
2626     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2627         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
2628     if (isCallingPerm) {
2629         if (AAFwk::PermissionVerification::GetInstance()->IsGatewayCall()) {
2630             return ERR_OK;
2631         }
2632         auto callerUid = IPCSkeleton::GetCallingUid();
2633         auto appRecord = GetAppRunningRecordByAbilityToken(token);
2634         if (!appRecord || appRecord->GetUid() != callerUid) {
2635             HILOG_ERROR("Permission verification failed.");
2636             return ERR_PERMISSION_DENIED;
2637         }
2638     } else {
2639         HILOG_ERROR("Permission verification failed.");
2640         return ERR_PERMISSION_DENIED;
2641     }
2642 
2643     return ERR_OK;
2644 }
2645 
VerifyAPL() const2646 bool AppMgrServiceInner::VerifyAPL() const
2647 {
2648     if (!appRunningManager_) {
2649         HILOG_ERROR("appRunningManager_ is nullptr");
2650         return false;
2651     }
2652 
2653     auto callerPid = IPCSkeleton::GetCallingPid();
2654     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
2655     if (!appRecord) {
2656         HILOG_ERROR("Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
2657         return false;
2658     }
2659 
2660     auto applicationInfo = appRecord->GetApplicationInfo();
2661     if (!applicationInfo) {
2662         HILOG_ERROR("Get application info failed.");
2663         return false;
2664     }
2665 
2666     auto apl = applicationInfo->appPrivilegeLevel;
2667     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
2668         HILOG_ERROR("caller is not system_basic or system_core.");
2669         return false;
2670     }
2671     return true;
2672 }
2673 
VerifyAccountPermission(const std::string & permissionName,const int userId) const2674 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId) const
2675 {
2676     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2677     if (isSaCall) {
2678         return ERR_OK;
2679     }
2680 
2681     const int currentUserId = (int)(getuid() / Constants::BASE_USER_RANGE);
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 }  // namespace AppExecFwk
3118 }  // namespace OHOS
3119