• 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 "application_state_observer_stub.h"
24 #include "datetime_ex.h"
25 #include "hilog_wrapper.h"
26 #include "perf_profile.h"
27 
28 #include "app_process_data.h"
29 #include "bundle_constants.h"
30 #include "bytrace.h"
31 #include "common_event.h"
32 #include "common_event_manager.h"
33 #include "common_event_support.h"
34 #include "hisysevent.h"
35 #include "in_process_call_wrapper.h"
36 #include "ipc_skeleton.h"
37 #include "iremote_object.h"
38 #include "iservice_registry.h"
39 #include "itest_observer.h"
40 #include "os_account_manager.h"
41 #include "permission/permission_kit.h"
42 #include "permission_constants.h"
43 #include "permission_verification.h"
44 #include "system_ability_definition.h"
45 #ifdef SUPPORT_GRAPHICS
46 #include "locale_config.h"
47 #endif
48 #include "uri_permission_manager_client.h"
49 
50 
51 namespace OHOS {
52 namespace AppExecFwk {
53 using namespace OHOS::Security;
54 
55 namespace {
56 // NANOSECONDS mean 10^9 nano second
57 constexpr int64_t NANOSECONDS = 1000000000;
58 // MICROSECONDS mean 10^6 millias second
59 constexpr int64_t MICROSECONDS = 1000000;
60 // Kill process timeout setting
61 constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000;
62 // Kill process delaytime setting
63 constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200;
64 const std::string CLASS_NAME = "ohos.app.MainThread";
65 const std::string FUNC_NAME = "main";
66 const std::string SO_PATH = "system/lib64/libmapleappkit.z.so";
67 const std::string RENDER_PARAM = "invalidparam";
68 const int32_t SIGNAL_KILL = 9;
69 constexpr int32_t USER_SCALE = 200000;
70 #define ENUM_TO_STRING(s) #s
71 
72 constexpr int32_t BASE_USER_RANGE = 200000;
73 
74 constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01);
75 constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100; // error code for already exist render.
76 const std::string EVENT_NAME_LIFECYCLE_TIMEOUT = "LIFECYCLE_TIMEOUT";
77 constexpr char EVENT_KEY_UID[] = "UID";
78 constexpr char EVENT_KEY_PID[] = "PID";
79 constexpr char EVENT_KEY_PACKAGE_NAME[] = "PACKAGE_NAME";
80 constexpr char EVENT_KEY_PROCESS_NAME[] = "PROCESS_NAME";
81 constexpr char EVENT_KEY_MESSAGE[] = "MSG";
82 
83 // Msg length is less than 48 characters
84 const std::string EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!";
85 const std::string EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!";
86 const std::string EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT = "Add Ability Stage TimeOut!";
87 const std::string EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!";
88 const std::string EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT = "Start Process Specified Ability TimeOut!";
89 const std::string EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!";
90 
91 const std::string SYSTEM_BASIC = "system_basic";
92 const std::string SYSTEM_CORE = "system_core";
93 const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
94 
GetUserIdByUid(int32_t uid)95 int32_t GetUserIdByUid(int32_t uid)
96 {
97     return uid / BASE_USER_RANGE;
98 }
99 }  // namespace
100 
101 using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED;
102 using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
103 using OHOS::AppExecFwk::Constants::ROOT_UID;
104 
AppMgrServiceInner()105 AppMgrServiceInner::AppMgrServiceInner()
106     : appProcessManager_(std::make_shared<AppProcessManager>()),
107       remoteClientManager_(std::make_shared<RemoteClientManager>()),
108       appRunningManager_(std::make_shared<AppRunningManager>()),
109       configuration_(std::make_shared<Configuration>())
110 {}
111 
Init()112 void AppMgrServiceInner::Init()
113 {
114     GetGlobalConfiguration();
115 }
116 
~AppMgrServiceInner()117 AppMgrServiceInner::~AppMgrServiceInner()
118 {}
119 
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)120 void AppMgrServiceInner::LoadAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
121     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo,
122     const std::shared_ptr<AAFwk::Want> &want)
123 {
124     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
125     if (!CheckLoadabilityConditions(token, abilityInfo, appInfo)) {
126         HILOG_ERROR("CheckLoadabilityConditions failed");
127         return;
128     }
129 
130     if (!appRunningManager_) {
131         HILOG_ERROR("appRunningManager_ is nullptr");
132         return;
133     }
134 
135     BundleInfo bundleInfo;
136     HapModuleInfo hapModuleInfo;
137     if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo)) {
138         HILOG_ERROR("GetBundleAndHapInfo failed");
139         return;
140     }
141 
142     std::string processName;
143     MakeProcessName(processName, abilityInfo, appInfo, hapModuleInfo);
144     HILOG_INFO("processName = [%{public}s]", processName.c_str());
145 
146     auto appRecord =
147         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
148     if (!appRecord) {
149         appRecord =
150             CreateAppRunningRecord(token, preToken, appInfo, abilityInfo,
151                 processName, bundleInfo, hapModuleInfo, want);
152         if (!appRecord) {
153             HILOG_ERROR("CreateAppRunningRecord failed, appRecord is nullptr");
154             return;
155         }
156         bool isColdStart = want == nullptr ? false : want->GetBoolParam("coldStart", false);
157         StartProcess(abilityInfo->applicationName, processName, isColdStart, appRecord,
158             appInfo->uid, appInfo->bundleName);
159     } else {
160         StartAbility(token, preToken, abilityInfo, appRecord, hapModuleInfo, want);
161     }
162     PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
163     PerfProfile::GetInstance().Dump();
164     PerfProfile::GetInstance().Reset();
165 }
166 
CheckLoadabilityConditions(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo)167 bool AppMgrServiceInner::CheckLoadabilityConditions(const sptr<IRemoteObject> &token,
168     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo)
169 {
170     if (!token || !abilityInfo || !appInfo) {
171         HILOG_ERROR("param error");
172         return false;
173     }
174     if (abilityInfo->name.empty() || appInfo->name.empty()) {
175         HILOG_ERROR("error abilityInfo or appInfo");
176         return false;
177     }
178     if (abilityInfo->applicationName != appInfo->name) {
179         HILOG_ERROR("abilityInfo and appInfo have different appName, don't load for it");
180         return false;
181     }
182 
183     return true;
184 }
185 
MakeProcessName(std::string & processName,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,HapModuleInfo & hapModuleInfo)186 void AppMgrServiceInner::MakeProcessName(std::string &processName, const std::shared_ptr<AbilityInfo> &abilityInfo,
187     const std::shared_ptr<ApplicationInfo> &appInfo, HapModuleInfo &hapModuleInfo)
188 {
189     if (!abilityInfo || !appInfo) {
190         return;
191     }
192     if (!abilityInfo->process.empty()) {
193         processName = abilityInfo->process;
194         return;
195     }
196     MakeProcessName(processName, appInfo, hapModuleInfo);
197 }
198 
MakeProcessName(std::string & processName,const std::shared_ptr<ApplicationInfo> & appInfo,HapModuleInfo & hapModuleInfo)199 void AppMgrServiceInner::MakeProcessName(
200     std::string &processName, const std::shared_ptr<ApplicationInfo> &appInfo, HapModuleInfo &hapModuleInfo)
201 {
202     if (!appInfo) {
203         return;
204     }
205     if (!appInfo->process.empty()) {
206         processName = appInfo->process;
207         return;
208     }
209     // check after abilityInfo, because abilityInfo contains extension process.
210     if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()) {
211         processName = hapModuleInfo.process;
212         HILOG_INFO("Stage mode, Make processName:%{public}s", processName.c_str());
213         return;
214     }
215     processName = appInfo->bundleName;
216 }
217 
GetBundleAndHapInfo(const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)218 bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo,
219     const std::shared_ptr<ApplicationInfo> &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
220 {
221     HILOG_INFO("AppMgrServiceInner GetBundleAndHapInfo start!");
222     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
223     if (bundleMgr_ == nullptr) {
224         HILOG_ERROR("GetBundleManager fail");
225         return false;
226     }
227 
228     auto userId = GetUserIdByUid(appInfo->uid);
229     bool bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfo(appInfo->bundleName,
230         BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
231     if (!bundleMgrResult) {
232         HILOG_ERROR("GetBundleInfo is fail");
233         return false;
234     }
235     bundleMgrResult = bundleMgr_->GetHapModuleInfo(abilityInfo, hapModuleInfo);
236     if (!bundleMgrResult) {
237         HILOG_ERROR("GetHapModuleInfo is fail");
238         return false;
239     }
240 
241     return true;
242 }
243 
AttachApplication(const pid_t pid,const sptr<IAppScheduler> & app)244 void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &app)
245 {
246     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
247     if (pid <= 0) {
248         HILOG_ERROR("invalid pid:%{public}d", pid);
249         return;
250     }
251     if (!app) {
252         HILOG_ERROR("app client is null");
253         return;
254     }
255     HILOG_INFO("attach application pid:%{public}d", pid);
256     auto appRecord = GetAppRunningRecordByPid(pid);
257     if (!appRecord) {
258         HILOG_ERROR("no such appRecord");
259         return;
260     }
261     appRecord->SetApplicationClient(app);
262     if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
263         LaunchApplication(appRecord);
264     }
265     appRecord->RegisterAppDeathRecipient();
266 }
267 
LaunchApplication(const std::shared_ptr<AppRunningRecord> & appRecord)268 void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
269 {
270     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
271     if (!appRecord) {
272         HILOG_ERROR("appRecord is null");
273         return;
274     }
275 
276     if (!configuration_) {
277         HILOG_ERROR("configuration_ is null");
278         return;
279     }
280 
281     if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
282         HILOG_ERROR("wrong app state:%{public}d", appRecord->GetState());
283         return;
284     }
285     appRecord->LaunchApplication(*configuration_);
286     appRecord->SetState(ApplicationState::APP_STATE_READY);
287 
288     // There is no ability when the resident process starts
289     // The status of all resident processes is ready
290     // There is no process of switching the foreground, waiting for his first ability to start
291     if (appRecord->IsKeepAliveApp()) {
292         appRecord->AddAbilityStage();
293         return;
294     }
295 
296     if (appRecord->IsStartSpecifiedAbility()) {
297         appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
298         return;
299     }
300     appRecord->LaunchPendingAbilities();
301 }
302 
AddAbilityStageDone(const int32_t recordId)303 void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId)
304 {
305     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
306     if (!appRecord) {
307         HILOG_ERROR("get app record failed");
308         return;
309     }
310     appRecord->AddAbilityStageDone();
311 }
312 
ApplicationForegrounded(const int32_t recordId)313 void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId)
314 {
315     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
316     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
317     if (!appRecord) {
318         HILOG_ERROR("get app record failed");
319         return;
320     }
321     appRecord->PopForegroundingAbilityTokens();
322     ApplicationState appState = appRecord->GetState();
323     if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) {
324         appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND);
325         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND);
326     } else if (appState == ApplicationState::APP_STATE_SUSPENDED) {
327         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
328     } else {
329         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
330             appRecord->GetName().c_str(),
331             static_cast<ApplicationState>(appState));
332     }
333 
334     // push the foregrounded app front of RecentAppList.
335     PushAppFront(recordId);
336     HILOG_INFO("application is foregrounded");
337 }
338 
ApplicationBackgrounded(const int32_t recordId)339 void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId)
340 {
341     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
342     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
343     if (!appRecord) {
344         HILOG_ERROR("get app record failed");
345         return;
346     }
347     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
348         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
349         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND);
350     } else if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) {
351         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
352     } else {
353         HILOG_WARN("app name(%{public}s), app state(%{public}d)!",
354             appRecord->GetName().c_str(),
355             static_cast<ApplicationState>(appRecord->GetState()));
356     }
357 
358     HILOG_INFO("application is backgrounded");
359 }
360 
ApplicationTerminated(const int32_t recordId)361 void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
362 {
363     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
364     if (!appRunningManager_) {
365         HILOG_ERROR("appRunningManager_ is nullptr");
366         return;
367     }
368 
369     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
370     if (!appRecord) {
371         HILOG_ERROR("get app record failed");
372         return;
373     }
374     appRecord->ApplicationTerminated();
375     // Maybe can't get in here
376     if (appRecord->IsKeepAliveApp()) {
377         return;
378     }
379     if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
380         HILOG_ERROR("current state is not background");
381         return;
382     }
383     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
384     appRecord->RemoveAppDeathRecipient();
385     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED);
386     appRunningManager_->RemoveAppRunningRecordById(recordId);
387     RemoveAppFromRecentListById(recordId);
388     OnProcessDied(appRecord);
389 
390     HILOG_INFO("application is terminated");
391 }
392 
KillApplication(const std::string & bundleName)393 int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName)
394 {
395     if (!appRunningManager_) {
396         HILOG_ERROR("appRunningManager_ is nullptr");
397         return ERR_NO_INIT;
398     }
399 
400     auto errCode = VerifyProcessPermission();
401     if (errCode != ERR_OK) {
402         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
403         return errCode;
404     }
405 
406     int result = ERR_OK;
407     int64_t startTime = SystemTimeMillis();
408     std::list<pid_t> pids;
409 
410     if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids)) {
411         HILOG_INFO("The process corresponding to the package name did not start");
412         return result;
413     }
414     if (WaitForRemoteProcessExit(pids, startTime)) {
415         HILOG_INFO("The remote process exited successfully ");
416         NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
417         return result;
418     }
419     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
420         result = KillProcessByPid(*iter);
421         if (result < 0) {
422             HILOG_ERROR("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter);
423             return result;
424         }
425     }
426     NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
427     return result;
428 }
429 
KillApplicationByUid(const std::string & bundleName,const int uid)430 int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid)
431 {
432     if (!appRunningManager_) {
433         HILOG_ERROR("appRunningManager_ is nullptr");
434         return ERR_NO_INIT;
435     }
436 
437     auto errCode = VerifyProcessPermission();
438     if (errCode != ERR_OK) {
439         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
440         return errCode;
441     }
442 
443     int result = ERR_OK;
444     int64_t startTime = SystemTimeMillis();
445     std::list<pid_t> pids;
446     if (remoteClientManager_ == nullptr) {
447         HILOG_ERROR("remoteClientManager_ fail");
448         return ERR_NO_INIT;
449     }
450     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
451     if (bundleMgr_ == nullptr) {
452         HILOG_ERROR("GetBundleManager fail");
453         return ERR_NO_INIT;
454     }
455     HILOG_INFO("uid value is %{public}d", uid);
456     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
457         HILOG_INFO("The process corresponding to the package name did not start");
458         return result;
459     }
460     if (WaitForRemoteProcessExit(pids, startTime)) {
461         HILOG_INFO("The remote process exited successfully ");
462         return result;
463     }
464     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
465         result = KillProcessByPid(*iter);
466         if (result < 0) {
467             HILOG_ERROR("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter);
468             return result;
469         }
470     }
471     return result;
472 }
473 
KillApplicationByUserId(const std::string & bundleName,const int userId)474 int32_t AppMgrServiceInner::KillApplicationByUserId(const std::string &bundleName, const int userId)
475 {
476     if (!appRunningManager_) {
477         HILOG_ERROR("appRunningManager_ is nullptr");
478         return ERR_NO_INIT;
479     }
480 
481     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES, userId) ==
482         ERR_PERMISSION_DENIED) {
483         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
484         return ERR_PERMISSION_DENIED;
485     }
486 
487     if (remoteClientManager_ == nullptr) {
488         HILOG_ERROR("remoteClientManager_ fail");
489         return ERR_NO_INIT;
490     }
491     auto bundleMgr = remoteClientManager_->GetBundleManager();
492     if (bundleMgr == nullptr) {
493         HILOG_ERROR("GetBundleManager fail");
494         return ERR_NO_INIT;
495     }
496 
497     int32_t callerUid = IPCSkeleton::GetCallingUid();
498     if (!IN_PROCESS_CALL(bundleMgr->CheckIsSystemAppByUid(callerUid))) {
499         HILOG_ERROR("caller is not systemApp, callerUid %{public}d", callerUid);
500         return ERR_INVALID_VALUE;
501     }
502 
503     return KillApplicationByUserIdLocked(bundleName, userId);
504 }
505 
KillApplicationByUserIdLocked(const std::string & bundleName,const int userId)506 int32_t AppMgrServiceInner::KillApplicationByUserIdLocked(const std::string &bundleName, const int userId)
507 {
508     if (!appRunningManager_) {
509         HILOG_ERROR("appRunningManager_ is nullptr");
510         return ERR_NO_INIT;
511     }
512 
513     int result = ERR_OK;
514     int64_t startTime = SystemTimeMillis();
515     std::list<pid_t> pids;
516     if (remoteClientManager_ == nullptr) {
517         HILOG_ERROR("remoteClientManager_ fail");
518         return ERR_NO_INIT;
519     }
520     auto bundleMgr = remoteClientManager_->GetBundleManager();
521     if (bundleMgr == nullptr) {
522         HILOG_ERROR("GetBundleManager fail");
523         return ERR_NO_INIT;
524     }
525 
526     HILOG_INFO("userId value is %{public}d", userId);
527     int uid = IN_PROCESS_CALL(bundleMgr->GetUidByBundleName(bundleName, userId));
528     HILOG_INFO("uid value is %{public}d", uid);
529     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
530         HILOG_INFO("The process corresponding to the package name did not start");
531         return result;
532     }
533     if (WaitForRemoteProcessExit(pids, startTime)) {
534         HILOG_INFO("The remote process exited successfully ");
535         return result;
536     }
537     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
538         result = KillProcessByPid(*iter);
539         if (result < 0) {
540             HILOG_ERROR("KillApplication is fail bundleName: %{public}s pid: %{public}d", bundleName.c_str(), *iter);
541             return result;
542         }
543     }
544     return result;
545 }
546 
ClearUpApplicationData(const std::string & bundleName,int32_t callerUid,pid_t callerPid)547 void AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName, int32_t callerUid, pid_t callerPid)
548 {
549     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
550     auto userId = GetUserIdByUid(callerUid);
551     HILOG_INFO("userId:%{public}d", userId);
552     ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, userId);
553 }
554 
ClearUpApplicationDataByUserId(const std::string & bundleName,int32_t callerUid,pid_t callerPid,const int userId)555 void AppMgrServiceInner::ClearUpApplicationDataByUserId(
556     const std::string &bundleName, int32_t callerUid, pid_t callerPid, const int userId)
557 {
558     if (callerPid <= 0) {
559         HILOG_ERROR("invalid callerPid:%{public}d", callerPid);
560         return;
561     }
562     if (callerUid <= 0) {
563         HILOG_ERROR("invalid callerUid:%{public}d", callerUid);
564         return;
565     }
566     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
567     if (bundleMgr_ == nullptr) {
568         HILOG_ERROR("GetBundleManager fail");
569         return;
570     }
571 
572     // request to clear user information permission.
573     int32_t result =
574         Permission::PermissionKit::RemoveUserGrantedReqPermissions(bundleName, userId);
575     if (result) {
576         HILOG_ERROR("RemoveUserGrantedReqPermissions failed");
577         return;
578     }
579     // 2.delete bundle side user data
580     if (!IN_PROCESS_CALL(bundleMgr_->CleanBundleDataFiles(bundleName, userId))) {
581         HILOG_ERROR("Delete bundle side user data is fail");
582         return;
583     }
584     // 3.kill application
585     // 4.revoke user rights
586     result = KillApplicationByUserId(bundleName, userId);
587     if (result < 0) {
588         HILOG_ERROR("Kill Application by bundle name is fail");
589         return;
590     }
591     NotifyAppStatusByCallerUid(bundleName, userId, callerUid,
592         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
593 }
594 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)595 int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
596 {
597     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
598 
599     std::vector<int32_t> ids;
600     auto result = AccountSA::OsAccountManager::QueryActiveOsAccountIds(ids);
601     HILOG_DEBUG("ids size : %{public}d", static_cast<int>(ids.size()));
602 
603     // check permission
604     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
605         const auto &appRecord = item.second;
606         int32_t userId = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
607         if ((std::find(ids.begin(), ids.end(), userId) != ids.end()) && (result == ERR_OK)) {
608             if (isPerm) {
609                 GetRunningProcesses(appRecord, info);
610             } else {
611                 auto applicationInfo = appRecord->GetApplicationInfo();
612                 if (!applicationInfo) {
613                     continue;
614                 }
615                 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
616                 auto tokenId = applicationInfo->accessTokenId;
617                 if (callingTokenId == tokenId) {
618                     GetRunningProcesses(appRecord, info);
619                 }
620             }
621         }
622     }
623     return ERR_OK;
624 }
625 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)626 int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
627 {
628     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
629         ERR_PERMISSION_DENIED) {
630         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
631         return ERR_PERMISSION_DENIED;
632     }
633 
634     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
635         const auto &appRecord = item.second;
636         int32_t userIdTemp = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
637         if (userIdTemp == userId) {
638             GetRunningProcesses(appRecord, info);
639         }
640     }
641     return ERR_OK;
642 }
643 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)644 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
645     std::vector<RunningProcessInfo> &info)
646 {
647     RunningProcessInfo runningProcessInfo;
648     runningProcessInfo.processName_ = appRecord->GetProcessName();
649     runningProcessInfo.pid_ = appRecord->GetPriorityObject()->GetPid();
650     runningProcessInfo.uid_ = appRecord->GetUid();
651     runningProcessInfo.state_ = static_cast<AppProcessState>(appRecord->GetState());
652     appRecord->GetBundleNames(runningProcessInfo.bundleNames);
653     info.emplace_back(runningProcessInfo);
654 }
655 
KillProcessByPid(const pid_t pid) const656 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid) const
657 {
658     int32_t ret = -1;
659     if (pid > 0) {
660         HILOG_INFO("kill pid %{public}d", pid);
661         ret = kill(pid, SIGNAL_KILL);
662     }
663     return ret;
664 }
665 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)666 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
667 {
668     int64_t delayTime = SystemTimeMillis() - startTime;
669     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
670         if (CheckAllProcessExist(pids)) {
671             return true;
672         }
673         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
674         delayTime = SystemTimeMillis() - startTime;
675     }
676     return false;
677 }
678 
GetAllPids(std::list<pid_t> & pids)679 bool AppMgrServiceInner::GetAllPids(std::list<pid_t> &pids)
680 {
681     for (const auto &appTaskInfo : appProcessManager_->GetRecentAppList()) {
682         if (appTaskInfo) {
683             auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
684             if (appRecord) {
685                 pids.push_back(appTaskInfo->GetPid());
686                 appRecord->ScheduleProcessSecurityExit();
687             }
688         }
689     }
690     return (pids.empty() ? false : true);
691 }
692 
process_exist(pid_t & pid)693 bool AppMgrServiceInner::process_exist(pid_t &pid)
694 {
695     char pid_path[128] = {0};
696     struct stat stat_buf;
697     if (!pid) {
698         return false;
699     }
700     if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) {
701         return false;
702     }
703     if (stat(pid_path, &stat_buf) == 0) {
704         return true;
705     }
706     return false;
707 }
708 
CheckAllProcessExist(std::list<pid_t> & pids)709 bool AppMgrServiceInner::CheckAllProcessExist(std::list<pid_t> &pids)
710 {
711     for (auto iter = pids.begin(); iter != pids.end();) {
712         if (!process_exist(*iter)) {
713             iter = pids.erase(iter);
714         } else {
715             iter++;
716         }
717     }
718     if (pids.empty()) {
719         return true;
720     }
721     return false;
722 }
723 
SystemTimeMillis()724 int64_t AppMgrServiceInner::SystemTimeMillis()
725 {
726     struct timespec t;
727     t.tv_sec = 0;
728     t.tv_nsec = 0;
729     clock_gettime(CLOCK_MONOTONIC, &t);
730     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
731 }
732 
GetAppRunningRecordByPid(const pid_t pid) const733 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
734 {
735     return appRunningManager_->GetAppRunningRecordByPid(pid);
736 }
737 
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)738 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(const sptr<IRemoteObject> &token,
739     const sptr<IRemoteObject> &preToken, const std::shared_ptr<ApplicationInfo> &appInfo,
740     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
741     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
742 {
743     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
744     if (!appRunningManager_) {
745         return nullptr;
746     }
747     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
748     if (!appRecord) {
749         return nullptr;
750     }
751 
752     appRecord->SetEventHandler(eventHandler_);
753     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
754     if (want) {
755         appRecord->SetDebugApp(want->GetBoolParam("debugApp", false));
756     }
757 
758     if (preToken) {
759         auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
760         if (abilityRecord) {
761             abilityRecord->SetPreToken(preToken);
762         }
763     }
764 
765     return appRecord;
766 }
767 
TerminateAbility(const sptr<IRemoteObject> & token)768 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token)
769 {
770     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
771     HILOG_DEBUG("AppMgrServiceInner::TerminateAbility begin");
772     if (!token) {
773         HILOG_ERROR("AppMgrServiceInner::TerminateAbility token is null!");
774         return;
775     }
776     auto appRecord = GetAppRunningRecordByAbilityToken(token);
777     if (!appRecord) {
778         HILOG_ERROR("AppMgrServiceInner::TerminateAbility app is not exist!");
779         return;
780     }
781     if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) {
782         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
783     }
784 
785     if (appRunningManager_) {
786         appRunningManager_->TerminateAbility(token);
787     }
788 }
789 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)790 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
791 {
792     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
793     if (!token) {
794         HILOG_ERROR("token is null!");
795         return;
796     }
797 
798     auto appRecord = GetAppRunningRecordByAbilityToken(token);
799     if (!appRecord) {
800         HILOG_ERROR("app is not exist!");
801         return;
802     }
803     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
804     if (!abilityRecord) {
805         HILOG_ERROR("can not find ability record!");
806         return;
807     }
808     if (state == abilityRecord->GetState()) {
809         HILOG_ERROR("current state is already, no need update!");
810         return;
811     }
812     auto type = abilityRecord->GetAbilityInfo()->type;
813     if (type == AppExecFwk::AbilityType::SERVICE &&
814         (state == AbilityState::ABILITY_STATE_CREATE ||
815         state == AbilityState::ABILITY_STATE_TERMINATED ||
816         state == AbilityState::ABILITY_STATE_CONNECTED ||
817         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
818         HILOG_INFO("StateChangedNotifyObserver service type, state:%{public}d", static_cast<int32_t>(state));
819         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true);
820         return;
821     }
822     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
823         HILOG_ERROR("state is not foreground or background!");
824         return;
825     }
826     if (appRecord->GetState() == ApplicationState::APP_STATE_SUSPENDED) {
827         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
828     }
829 
830     appRecord->UpdateAbilityState(token, state);
831 }
832 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)833 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
834 {
835     if (!token) {
836         HILOG_ERROR("token is null!");
837         return;
838     }
839     auto appRecord = GetAppRunningRecordByAbilityToken(token);
840     if (!appRecord) {
841         HILOG_ERROR("app is not exist!");
842         return;
843     }
844     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
845     if (!abilityRecord) {
846         HILOG_ERROR("can not find ability record!");
847         return;
848     }
849     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false);
850 }
851 
OnStop()852 void AppMgrServiceInner::OnStop()
853 {
854     appRunningManager_->ClearAppRunningRecordMap();
855     CloseAppSpawnConnection();
856 }
857 
OpenAppSpawnConnection()858 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
859 {
860     if (remoteClientManager_->GetSpawnClient()) {
861         return remoteClientManager_->GetSpawnClient()->OpenConnection();
862     }
863     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
864 }
865 
CloseAppSpawnConnection() const866 void AppMgrServiceInner::CloseAppSpawnConnection() const
867 {
868     if (remoteClientManager_->GetSpawnClient()) {
869         remoteClientManager_->GetSpawnClient()->CloseConnection();
870     }
871 }
872 
QueryAppSpawnConnectionState() const873 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
874 {
875     if (remoteClientManager_->GetSpawnClient()) {
876         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
877     }
878     return SpawnConnectionState::STATE_NOT_CONNECT;
879 }
880 
GetRecordMap() const881 const std::map<const int32_t, const std::shared_ptr<AppRunningRecord>> &AppMgrServiceInner::GetRecordMap() const
882 {
883     return appRunningManager_->GetAppRunningRecordMap();
884 }
885 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)886 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
887 {
888     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
889 }
890 
SetBundleManager(sptr<IBundleMgr> bundleManager)891 void AppMgrServiceInner::SetBundleManager(sptr<IBundleMgr> bundleManager)
892 {
893     remoteClientManager_->SetBundleManager(bundleManager);
894 }
895 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)896 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback> &callback)
897 {
898     pid_t callingPid = IPCSkeleton::GetCallingPid();
899     pid_t pid = getpid();
900     if (callingPid != pid) {
901         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
902         return;
903     }
904     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
905     if (callback != nullptr) {
906         appStateCallbacks_.push_back(callback);
907     }
908 }
909 
AbilityBehaviorAnalysis(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const int32_t visibility,const int32_t perceptibility,const int32_t connectionState)910 void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
911     const int32_t visibility,       // 0:false,1:true
912     const int32_t perceptibility,   // 0:false,1:true
913     const int32_t connectionState)  // 0:false,1:true
914 {
915     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
916     if (!token) {
917         HILOG_ERROR("token is null");
918         return;
919     }
920     auto appRecord = GetAppRunningRecordByAbilityToken(token);
921     if (!appRecord) {
922         HILOG_ERROR("app record is not exist for ability token");
923         return;
924     }
925     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
926     if (!abilityRecord) {
927         HILOG_ERROR("ability record is not exist for ability previous token");
928         return;
929     }
930     if (preToken) {
931         abilityRecord->SetPreToken(preToken);
932     }
933     abilityRecord->SetVisibility(visibility);
934     abilityRecord->SetPerceptibility(perceptibility);
935     abilityRecord->SetConnectionState(connectionState);
936 }
937 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)938 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
939 {
940     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
941     if (!token) {
942         HILOG_ERROR("token is null");
943         return;
944     }
945     auto appRecord = GetAppRunningRecordByAbilityToken(token);
946     if (!appRecord) {
947         HILOG_ERROR("app record is not exist for ability token");
948         return;
949     }
950 
951     // before exec ScheduleProcessSecurityExit return
952     // The resident process won't let him die
953     if (appRecord->IsKeepAliveApp()) {
954         return;
955     }
956 
957     std::list<pid_t> pids;
958     pid_t pid = appRecord->GetPriorityObject()->GetPid();
959     if (pid > 0) {
960         pids.push_back(pid);
961         appRecord->ScheduleProcessSecurityExit();
962         if (!WaitForRemoteProcessExit(pids, SystemTimeMillis())) {
963             int32_t result = KillProcessByPid(pid);
964             if (result < 0) {
965                 HILOG_ERROR("KillProcessByAbilityToken kill process is fail");
966                 return;
967             }
968         }
969     }
970 }
971 
KillProcessesByUserId(int32_t userId)972 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId)
973 {
974     if (!appRunningManager_) {
975         HILOG_ERROR("appRunningManager_ is nullptr");
976         return;
977     }
978 
979     int64_t startTime = SystemTimeMillis();
980     std::list<pid_t> pids;
981     if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
982         HILOG_INFO("The process corresponding to the userId did not start");
983         return;
984     }
985     if (WaitForRemoteProcessExit(pids, startTime)) {
986         HILOG_INFO("The remote process exited successfully ");
987         return;
988     }
989     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
990         auto result = KillProcessByPid(*iter);
991         if (result < 0) {
992             HILOG_ERROR("KillProcessByPid is failed. pid: %{public}d", *iter);
993             return;
994         }
995     }
996 }
997 
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)998 void AppMgrServiceInner::StartAbility(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
999     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<AppRunningRecord> &appRecord,
1000     const HapModuleInfo &hapModuleInfo, const std::shared_ptr<AAFwk::Want> &want)
1001 {
1002     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
1003     HILOG_INFO("already create appRecord, just start ability");
1004     if (!appRecord) {
1005         HILOG_ERROR("appRecord is null");
1006         return;
1007     }
1008 
1009     if (abilityInfo->launchMode == LaunchMode::SINGLETON) {
1010         int32_t ownerUserId = -1;
1011         if (want) {
1012             ownerUserId = want->GetIntParam(ABILITY_OWNER_USERID, -1);
1013         }
1014         auto abilityRecord = appRecord->GetAbilityRunningRecord(abilityInfo->name, ownerUserId);
1015         if (abilityRecord) {
1016             HILOG_WARN("same ability info in singleton launch mode, will not add ability");
1017             return;
1018         }
1019     }
1020 
1021     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
1022     if (ability && preToken) {
1023         HILOG_ERROR("Ability is already started");
1024         ability->SetPreToken(preToken);
1025         return;
1026     }
1027 
1028     ApplicationState appState = appRecord->GetState();
1029     if (appState == ApplicationState::APP_STATE_SUSPENDED) {
1030         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
1031     }
1032 
1033     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
1034     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want);
1035     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
1036     if (!moduleRecord) {
1037         HILOG_ERROR("add moduleRecord failed");
1038         return;
1039     }
1040 
1041     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
1042     if (!ability) {
1043         HILOG_ERROR("add ability failed");
1044         return;
1045     }
1046 
1047     if (preToken != nullptr) {
1048         ability->SetPreToken(preToken);
1049     }
1050 
1051     if (appState == ApplicationState::APP_STATE_CREATE) {
1052         HILOG_ERROR("in create state, don't launch ability");
1053         return;
1054     }
1055     appRecord->LaunchAbility(ability);
1056 }
1057 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const1058 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
1059     const sptr<IRemoteObject> &abilityToken) const
1060 {
1061     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
1062 }
1063 
AbilityTerminated(const sptr<IRemoteObject> & token)1064 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
1065 {
1066     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
1067     HILOG_DEBUG("begin");
1068     if (!token) {
1069         HILOG_ERROR("token is null!");
1070         return;
1071     }
1072 
1073     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
1074     if (!appRecord) {
1075         HILOG_ERROR("app is not exist!");
1076         return;
1077     }
1078 
1079     appRecord->AbilityTerminated(token);
1080 }
1081 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const1082 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
1083 {
1084     const auto &iter = appRunningManager_->GetAppRunningRecordMap().find(recordId);
1085     if (iter != appRunningManager_->GetAppRunningRecordMap().end()) {
1086         return iter->second;
1087     }
1088     return nullptr;
1089 }
1090 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1091 void AppMgrServiceInner::OnAppStateChanged(
1092     const std::shared_ptr<AppRunningRecord> &appRecord, const ApplicationState state)
1093 {
1094     HILOG_DEBUG("begin, state:%{public}d", static_cast<int32_t>(state));
1095     if (!appRecord) {
1096         HILOG_ERROR("app record is null");
1097         return;
1098     }
1099 
1100     for (const auto &callback : appStateCallbacks_) {
1101         if (callback != nullptr) {
1102             callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
1103         }
1104     }
1105 
1106     if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) {
1107         AppStateData data = WrapAppStateData(appRecord, state);
1108         HILOG_DEBUG(
1109             "OnForegroundApplicationChanged, size:%{public}d, name:%{public}s, uid:%{public}d, state:%{public}d",
1110             (int32_t)appStateObservers_.size(), data.bundleName.c_str(), data.uid, data.state);
1111         std::lock_guard<std::recursive_mutex> lockNotify(observerLock_);
1112         for (const auto &observer : appStateObservers_) {
1113             if (observer != nullptr) {
1114                 observer->OnForegroundApplicationChanged(data);
1115             }
1116         }
1117     }
1118 
1119     if (state == ApplicationState::APP_STATE_CREATE || state == ApplicationState::APP_STATE_TERMINATED) {
1120         AppStateData data = WrapAppStateData(appRecord, state);
1121         HILOG_INFO("OnApplicationStateChanged, size:%{public}d, name:%{public}s, uid:%{public}d, state:%{public}d",
1122             (int32_t)appStateObservers_.size(), data.bundleName.c_str(), data.uid, data.state);
1123         std::lock_guard<std::recursive_mutex> lockNotify(observerLock_);
1124         for (const auto &observer : appStateObservers_) {
1125             if (observer != nullptr) {
1126                 observer->OnApplicationStateChanged(data);
1127             }
1128         }
1129     }
1130 }
1131 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1132 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
1133     const ApplicationState state)
1134 {
1135     AppProcessData processData;
1136     auto appInfoList = appRecord->GetAppInfoList();
1137     for (const auto &list : appInfoList) {
1138         AppData data;
1139         data.appName = list->name;
1140         data.uid = list->uid;
1141         processData.appDatas.push_back(data);
1142     }
1143     processData.processName = appRecord->GetProcessName();
1144     processData.pid = appRecord->GetPriorityObject()->GetPid();
1145     processData.appState = state;
1146     return processData;
1147 }
1148 
WrapAppStateData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)1149 AppStateData AppMgrServiceInner::WrapAppStateData(const std::shared_ptr<AppRunningRecord> &appRecord,
1150     const ApplicationState state)
1151 {
1152     AppStateData appStateData;
1153     appStateData.bundleName = appRecord->GetBundleName();
1154     appStateData.state = static_cast<int32_t>(state);
1155     appStateData.uid = appRecord->GetUid();
1156     return appStateData;
1157 }
1158 
WrapProcessData(const std::shared_ptr<AppRunningRecord> & appRecord)1159 ProcessData AppMgrServiceInner::WrapProcessData(const std::shared_ptr<AppRunningRecord> &appRecord)
1160 {
1161     ProcessData processData;
1162     processData.bundleName = appRecord->GetBundleName();
1163     processData.pid = appRecord->GetPriorityObject()->GetPid();
1164     processData.uid = appRecord->GetUid();
1165     return processData;
1166 }
1167 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)1168 void AppMgrServiceInner::OnAbilityStateChanged(
1169     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
1170 {
1171     HILOG_DEBUG("begin, state:%{public}d", static_cast<int32_t>(state));
1172     if (!ability) {
1173         HILOG_ERROR("ability is null");
1174         return;
1175     }
1176     for (const auto &callback : appStateCallbacks_) {
1177         if (callback != nullptr) {
1178             callback->OnAbilityRequestDone(ability->GetToken(), state);
1179         }
1180     }
1181 }
1182 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility)1183 void AppMgrServiceInner::StateChangedNotifyObserver(const AbilityStateData abilityStateData, bool isAbility)
1184 {
1185     std::lock_guard<std::recursive_mutex> lockNotify(observerLock_);
1186     HILOG_DEBUG("bundle:%{public}s, ability:%{public}s, state:%{public}d, pid:%{public}d,"
1187         "uid:%{public}d, abilityType:%{public}d",
1188         abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str(),
1189         abilityStateData.abilityState, abilityStateData.pid, abilityStateData.uid,
1190         abilityStateData.abilityType);
1191     for (const auto &observer : appStateObservers_) {
1192         if (observer != nullptr) {
1193             if (isAbility) {
1194                 observer->OnAbilityStateChanged(abilityStateData);
1195             } else {
1196                 observer->OnExtensionStateChanged(abilityStateData);
1197             }
1198         }
1199     }
1200 }
1201 
OnProcessCreated(const std::shared_ptr<AppRunningRecord> & appRecord)1202 void AppMgrServiceInner::OnProcessCreated(const std::shared_ptr<AppRunningRecord> &appRecord)
1203 {
1204     HILOG_DEBUG("OnProcessCreated begin.");
1205     if (!appRecord) {
1206         HILOG_ERROR("app record is null");
1207         return;
1208     }
1209     ProcessData data = WrapProcessData(appRecord);
1210     HILOG_DEBUG("OnProcessCreated, bundle:%{public}s, pid:%{public}d, uid:%{public}d, size:%{public}d",
1211         data.bundleName.c_str(), data.uid, data.pid, (int32_t)appStateObservers_.size());
1212     std::lock_guard<std::recursive_mutex> lockNotify(observerLock_);
1213     for (const auto &observer : appStateObservers_) {
1214         if (observer != nullptr) {
1215             observer->OnProcessCreated(data);
1216         }
1217     }
1218     HILOG_DEBUG("end");
1219 }
1220 
OnProcessDied(const std::shared_ptr<AppRunningRecord> & appRecord)1221 void AppMgrServiceInner::OnProcessDied(const std::shared_ptr<AppRunningRecord> &appRecord)
1222 {
1223     HILOG_DEBUG("OnProcessDied begin.");
1224     if (!appRecord) {
1225         HILOG_ERROR("app record is null");
1226         return;
1227     }
1228     ProcessData data = WrapProcessData(appRecord);
1229     HILOG_DEBUG("OnProcessDied, bundle:%{public}s, pid:%{public}d, uid:%{public}d, size:%{public}d",
1230         data.bundleName.c_str(), data.uid, data.pid, (int32_t)appStateObservers_.size());
1231     std::lock_guard<std::recursive_mutex> lockNotify(observerLock_);
1232     for (const auto &observer : appStateObservers_) {
1233         if (observer != nullptr) {
1234             observer->OnProcessDied(data);
1235         }
1236     }
1237     HILOG_DEBUG("end");
1238 }
1239 
StartProcess(const std::string & appName,const std::string & processName,bool coldStart,const std::shared_ptr<AppRunningRecord> & appRecord,const int uid,const std::string & bundleName)1240 void AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName, bool coldStart,
1241     const std::shared_ptr<AppRunningRecord> &appRecord, const int uid, const std::string &bundleName)
1242 {
1243     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
1244     if (!remoteClientManager_->GetSpawnClient() || !appRecord) {
1245         HILOG_ERROR("appSpawnClient or apprecord is null");
1246         return;
1247     }
1248 
1249     auto bundleMgr_ = remoteClientManager_->GetBundleManager();
1250     if (bundleMgr_ == nullptr) {
1251         HILOG_ERROR("GetBundleManager fail");
1252         return;
1253     }
1254 
1255     auto userId = GetUserIdByUid(uid);
1256     AppSpawnStartMsg startMsg;
1257     BundleInfo bundleInfo;
1258     std::vector<AppExecFwk::BundleInfo> bundleInfos;
1259     bool bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleInfos(AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES,
1260         bundleInfos, userId));
1261     if (!bundleMgrResult) {
1262         HILOG_ERROR("GetBundleInfo is fail");
1263         return;
1264     }
1265 
1266     auto isExist = [&bundleName, &uid](const AppExecFwk::BundleInfo &bundleInfo) {
1267         return bundleInfo.name == bundleName && bundleInfo.uid == uid;
1268     };
1269     auto bundleInfoIter = std::find_if(bundleInfos.begin(), bundleInfos.end(), isExist);
1270     if (bundleInfoIter == bundleInfos.end()) {
1271         HILOG_ERROR("Get target fail.");
1272         return;
1273     }
1274     startMsg.uid = (*bundleInfoIter).uid;
1275     startMsg.gid = (*bundleInfoIter).gid;
1276     startMsg.accessTokenId = (*bundleInfoIter).applicationInfo.accessTokenId;
1277     startMsg.apl = (*bundleInfoIter).applicationInfo.appPrivilegeLevel;
1278     startMsg.bundleName = bundleName;
1279     startMsg.renderParam = RENDER_PARAM;
1280     startMsg.coldStart = coldStart;
1281     HILOG_DEBUG("StartProcess accessTokenId:%{public}d, apl:%{public}s, bundleName:%{public}s coldStart:%{public}d",
1282         startMsg.accessTokenId, startMsg.apl.c_str(), bundleName.c_str(), coldStart);
1283 
1284     bundleMgrResult = IN_PROCESS_CALL(bundleMgr_->GetBundleGidsByUid(bundleName, uid, startMsg.gids));
1285     if (!bundleMgrResult) {
1286         HILOG_ERROR("GetBundleGids is fail");
1287         return;
1288     }
1289     startMsg.procName = processName;
1290     startMsg.soPath = SO_PATH;
1291 
1292     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
1293     pid_t pid = 0;
1294     ErrCode errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
1295     if (FAILED(errCode)) {
1296         HILOG_ERROR("failed to spawn new app process, errCode %{public}08x", errCode);
1297         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1298         return;
1299     }
1300     HILOG_INFO("newPid:%{public}d uid:%{public}d", pid, startMsg.uid);
1301     appRecord->GetPriorityObject()->SetPid(pid);
1302     appRecord->SetUid(startMsg.uid);
1303     appRecord->SetStartMsg(startMsg);
1304     appRecord->SetAppMgrServiceInner(weak_from_this());
1305     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE);
1306     AddAppToRecentList(appName, appRecord->GetProcessName(), pid, appRecord->GetRecordId());
1307     OnProcessCreated(appRecord);
1308     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
1309 }
1310 
RemoveAppFromRecentList(const std::string & appName,const std::string & processName)1311 void AppMgrServiceInner::RemoveAppFromRecentList(const std::string &appName, const std::string &processName)
1312 {
1313     int64_t startTime = 0;
1314     std::list<pid_t> pids;
1315     auto appTaskInfo = appProcessManager_->GetAppTaskInfoByProcessName(appName, processName);
1316     if (!appTaskInfo) {
1317         return;
1318     }
1319     auto appRecord = GetAppRunningRecordByPid(appTaskInfo->GetPid());
1320     if (!appRecord) {
1321         appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
1322         return;
1323     }
1324 
1325     // Do not delete resident processes, berfor exec ScheduleProcessSecurityExit
1326     if (appRecord->IsKeepAliveApp()) {
1327         return;
1328     }
1329 
1330     startTime = SystemTimeMillis();
1331     pids.push_back(appTaskInfo->GetPid());
1332     appRecord->ScheduleProcessSecurityExit();
1333     if (!WaitForRemoteProcessExit(pids, startTime)) {
1334         int32_t result = KillProcessByPid(appTaskInfo->GetPid());
1335         if (result < 0) {
1336             HILOG_ERROR("RemoveAppFromRecentList kill process is fail");
1337             return;
1338         }
1339     }
1340     appProcessManager_->RemoveAppFromRecentList(appTaskInfo);
1341 }
1342 
GetRecentAppList() const1343 const std::list<const std::shared_ptr<AppTaskInfo>> &AppMgrServiceInner::GetRecentAppList() const
1344 {
1345     return appProcessManager_->GetRecentAppList();
1346 }
1347 
ClearRecentAppList()1348 void AppMgrServiceInner::ClearRecentAppList()
1349 {
1350     int64_t startTime = 0;
1351     std::list<pid_t> pids;
1352     if (GetAllPids(pids)) {
1353         return;
1354     }
1355 
1356     startTime = SystemTimeMillis();
1357     if (WaitForRemoteProcessExit(pids, startTime)) {
1358         appProcessManager_->ClearRecentAppList();
1359         return;
1360     }
1361     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1362         int32_t result = KillProcessByPid(*iter);
1363         if (result < 0) {
1364             HILOG_ERROR("ClearRecentAppList kill process is fail");
1365             return;
1366         }
1367     }
1368     appProcessManager_->ClearRecentAppList();
1369 }
1370 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess)1371 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess)
1372 {
1373     HILOG_ERROR("On remote died.");
1374     if (isRenderProcess) {
1375         OnRenderRemoteDied(remote);
1376         return;
1377     }
1378 
1379     auto appRecord = appRunningManager_->OnRemoteDied(remote);
1380     if (!appRecord) {
1381         return;
1382     }
1383 
1384     FinishUserTestLocked("App died", -1, appRecord);
1385 
1386     // clear uri permission
1387     auto upmClient = AAFwk::UriPermissionManagerClient::GetInstance();
1388     auto appInfo = appRecord->GetApplicationInfo();
1389     if (appInfo && upmClient) {
1390         upmClient->RemoveUriPermission(appInfo->accessTokenId);
1391     }
1392 
1393     for (const auto &item : appRecord->GetAbilities()) {
1394         const auto &abilityRecord = item.second;
1395         appRecord->StateChangedNotifyObserver(abilityRecord,
1396             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true);
1397     }
1398     RemoveAppFromRecentListById(appRecord->GetRecordId());
1399     OnProcessDied(appRecord);
1400 
1401     // kill render if exist.
1402     auto renderRecord = appRecord->GetRenderRecord();
1403     if (renderRecord && renderRecord->GetPid() > 0) {
1404         HILOG_DEBUG("Kill render process when nwebhost died.");
1405         KillProcessByPid(renderRecord->GetPid());
1406     }
1407 
1408     if (appRecord->IsKeepAliveApp()) {
1409         appRecord->DecRestartResidentProcCount();
1410         if (appRecord->CanRestartResidentProc()) {
1411             auto restartProcss = [appRecord, innerService = shared_from_this()]() {
1412                 innerService->RestartResidentProcess(appRecord);
1413             };
1414 
1415             if (!eventHandler_) {
1416                 HILOG_ERROR("eventHandler_ is nullptr");
1417                 return;
1418             }
1419             eventHandler_->PostTask(restartProcss, "RestartResidentProcess");
1420         }
1421     }
1422 }
1423 
PushAppFront(const int32_t recordId)1424 void AppMgrServiceInner::PushAppFront(const int32_t recordId)
1425 {
1426     appProcessManager_->PushAppFront(recordId);
1427 }
1428 
RemoveAppFromRecentListById(const int32_t recordId)1429 void AppMgrServiceInner::RemoveAppFromRecentListById(const int32_t recordId)
1430 {
1431     appProcessManager_->RemoveAppFromRecentListById(recordId);
1432 }
1433 
AddAppToRecentList(const std::string & appName,const std::string & processName,const pid_t pid,const int32_t recordId)1434 void AppMgrServiceInner::AddAppToRecentList(
1435     const std::string &appName, const std::string &processName, const pid_t pid, const int32_t recordId)
1436 {
1437     appProcessManager_->AddAppToRecentList(appName, processName, pid, recordId);
1438 }
1439 
GetAppTaskInfoById(const int32_t recordId) const1440 const std::shared_ptr<AppTaskInfo> AppMgrServiceInner::GetAppTaskInfoById(const int32_t recordId) const
1441 {
1442     return appProcessManager_->GetAppTaskInfoById(recordId);
1443 }
1444 
AddAppDeathRecipient(const pid_t pid,const sptr<AppDeathRecipient> & appDeathRecipient) const1445 void AppMgrServiceInner::AddAppDeathRecipient(const pid_t pid, const sptr<AppDeathRecipient> &appDeathRecipient) const
1446 {
1447     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
1448     std::shared_ptr<AppRunningRecord> appRecord = GetAppRunningRecordByPid(pid);
1449     if (appRecord) {
1450         appRecord->SetAppDeathRecipient(appDeathRecipient);
1451     }
1452 }
1453 
HandleTimeOut(const InnerEvent::Pointer & event)1454 void AppMgrServiceInner::HandleTimeOut(const InnerEvent::Pointer &event)
1455 {
1456     HILOG_INFO("handle time out");
1457     if (!appRunningManager_ || event == nullptr) {
1458         HILOG_ERROR("appRunningManager or event is nullptr");
1459         return;
1460     }
1461     SendHiSysEvent(event->GetInnerEventId(), event->GetParam());
1462     switch (event->GetInnerEventId()) {
1463         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
1464             appRunningManager_->HandleTerminateTimeOut(event->GetParam());
1465             break;
1466         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
1467             HandleTerminateApplicationTimeOut(event->GetParam());
1468             break;
1469         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
1470         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
1471             HandleAddAbilityStageTimeOut(event->GetParam());
1472             break;
1473         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
1474             HandleStartSpecifiedAbilityTimeOut(event->GetParam());
1475             break;
1476         default:
1477             break;
1478     }
1479 }
1480 
SetEventHandler(const std::shared_ptr<AMSEventHandler> & handler)1481 void AppMgrServiceInner::SetEventHandler(const std::shared_ptr<AMSEventHandler> &handler)
1482 {
1483     eventHandler_ = handler;
1484 }
1485 
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)1486 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
1487 {
1488     BYTRACE_NAME(BYTRACE_TAG_APP, __PRETTY_FUNCTION__);
1489     HILOG_INFO("%{public}s called", __func__);
1490     if (!appRunningManager_) {
1491         HILOG_ERROR("appRunningManager_ is nullptr");
1492         return;
1493     }
1494     appRunningManager_->HandleAbilityAttachTimeOut(token);
1495 }
1496 
PrepareTerminate(const sptr<IRemoteObject> & token)1497 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token)
1498 {
1499     HILOG_INFO("Prepare terminate");
1500     if (!appRunningManager_) {
1501         HILOG_ERROR("appRunningManager_ is nullptr");
1502         return;
1503     }
1504     appRunningManager_->PrepareTerminate(token);
1505 }
1506 
HandleTerminateApplicationTimeOut(const int64_t eventId)1507 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId)
1508 {
1509     HILOG_INFO("handle terminate application time out");
1510     if (!appRunningManager_) {
1511         HILOG_ERROR("appRunningManager_ is nullptr");
1512         return;
1513     }
1514     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
1515     if (!appRecord) {
1516         HILOG_ERROR("appRecord is nullptr");
1517         return;
1518     }
1519     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
1520     appRecord->RemoveAppDeathRecipient();
1521     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED);
1522     pid_t pid = appRecord->GetPriorityObject()->GetPid();
1523     if (pid > 0) {
1524         int32_t result = KillProcessByPid(pid);
1525         if (result < 0) {
1526             HILOG_ERROR("KillProcessByAbilityToken kill process is fail");
1527             return;
1528         }
1529     }
1530     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
1531     RemoveAppFromRecentListById(appRecord->GetRecordId());
1532     OnProcessDied(appRecord);
1533 }
1534 
HandleAddAbilityStageTimeOut(const int64_t eventId)1535 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId)
1536 {
1537     HILOG_INFO("called add ability stage info time out!");
1538     if (!appRunningManager_) {
1539         HILOG_ERROR("appRunningManager_ is nullptr");
1540         return;
1541     }
1542     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
1543     if (!appRecord) {
1544         HILOG_ERROR("appRecord is nullptr");
1545         return;
1546     }
1547 
1548     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
1549         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
1550     }
1551 
1552     KillApplicationByRecord(appRecord);
1553 }
1554 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)1555 void AppMgrServiceInner::GetRunningProcessInfoByToken(
1556     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
1557 {
1558     HILOG_INFO("%{public}s called", __func__);
1559     if (!appRunningManager_) {
1560         HILOG_ERROR("appRunningManager_ is nullptr");
1561         return;
1562     }
1563 
1564     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1565     if (!isPerm) {
1566         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1567         return;
1568     }
1569 
1570     appRunningManager_->GetRunningProcessInfoByToken(token, info);
1571 }
1572 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)1573 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
1574 {
1575     HILOG_INFO("%{public}s called", __func__);
1576     pid_t callingPid = IPCSkeleton::GetCallingPid();
1577     pid_t pid = getpid();
1578     if (callingPid != pid) {
1579         HILOG_ERROR("%{public}s: Not SA call.", __func__);
1580         return;
1581     }
1582 
1583     HILOG_INFO("bundle info size: [%{public}d]", static_cast<int>(infos.size()));
1584     StartResidentProcess(infos, -1);
1585 }
1586 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount)1587 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount)
1588 {
1589     HILOG_INFO("start resident process");
1590     if (infos.empty()) {
1591         HILOG_ERROR("infos is empty!");
1592         return;
1593     }
1594 
1595     if (!appRunningManager_) {
1596         HILOG_ERROR("appRunningManager_ is nullptr");
1597         return;
1598     }
1599 
1600     for (auto &bundle : infos) {
1601         auto processName = bundle.applicationInfo.process.empty() ?
1602             bundle.applicationInfo.bundleName : bundle.applicationInfo.process;
1603         HILOG_INFO("processName = [%{public}s]", processName.c_str());
1604 
1605         // Inspection records
1606         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
1607             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
1608         if (appRecord) {
1609             HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
1610             continue;
1611         }
1612         StartEmptyResidentProcess(bundle, processName, restartCount);
1613     }
1614 }
1615 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount)1616 void AppMgrServiceInner::StartEmptyResidentProcess(
1617     const BundleInfo &info, const std::string &processName, int restartCount)
1618 {
1619     HILOG_INFO("start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
1620     if (!CheckRemoteClient() || !appRunningManager_) {
1621         HILOG_INFO("Failed to start resident process!");
1622         return;
1623     }
1624 
1625     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
1626     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
1627     if (!appRecord) {
1628         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
1629         return;
1630     }
1631 
1632     StartProcess(appInfo->name, processName, false, appRecord, appInfo->uid, appInfo->bundleName);
1633 
1634     // If it is empty, the startup failed
1635     if (!appRecord) {
1636         HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
1637         return;
1638     }
1639 
1640     bool isStageBased = false;
1641     bool moduelJson = false;
1642     if (!info.hapModuleInfos.empty()) {
1643         isStageBased = info.hapModuleInfos.back().isStageBasedModel;
1644         moduelJson = info.hapModuleInfos.back().isModuleJson;
1645     }
1646     HILOG_INFO("StartEmptyResidentProcess stage:%{public}d moduel:%{public}d size:%{public}d",
1647         isStageBased, moduelJson, (int32_t)info.hapModuleInfos.size());
1648     appRecord->SetKeepAliveAppState(true, isStageBased);
1649 
1650     if (restartCount > 0) {
1651         HILOG_INFO("StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount);
1652         appRecord->SetRestartResidentProcCount(restartCount);
1653     }
1654 
1655     appRecord->SetEventHandler(eventHandler_);
1656     appRecord->AddModules(appInfo, info.hapModuleInfos);
1657     HILOG_INFO("StartEmptyResidentProcess oK pid : [%{public}d], ", appRecord->GetPriorityObject()->GetPid());
1658 }
1659 
CheckRemoteClient()1660 bool AppMgrServiceInner::CheckRemoteClient()
1661 {
1662     if (!remoteClientManager_) {
1663         HILOG_ERROR("remoteClientManager_ is null");
1664         return false;
1665     }
1666 
1667     if (!remoteClientManager_->GetSpawnClient()) {
1668         HILOG_ERROR("appSpawnClient is null");
1669         return false;
1670     }
1671 
1672     if (!remoteClientManager_->GetBundleManager()) {
1673         HILOG_ERROR("GetBundleManager fail");
1674         return false;
1675     }
1676     return true;
1677 }
1678 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)1679 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
1680 {
1681     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
1682         HILOG_ERROR("restart resident process failed!");
1683         return;
1684     }
1685 
1686     auto bundleMgr = remoteClientManager_->GetBundleManager();
1687     BundleInfo bundleInfo;
1688     auto callerUid = IPCSkeleton::GetCallingUid();
1689     auto userId = GetUserIdByUid(callerUid);
1690     if (!IN_PROCESS_CALL(
1691         bundleMgr->GetBundleInfo(appRecord->GetBundleName(), BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
1692         HILOG_ERROR("GetBundleInfo fail");
1693         return;
1694     }
1695     std::vector<BundleInfo> infos;
1696     infos.emplace_back(bundleInfo);
1697     HILOG_INFO("the resident process [%{public}s] remaining restarts num is [%{public}d]",
1698         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
1699     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount());
1700 }
1701 
NotifyAppStatus(const std::string & bundleName,const std::string & eventData)1702 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData)
1703 {
1704     HILOG_INFO("%{public}s called, bundle name is %{public}s, event is %{public}s",
1705         __func__, bundleName.c_str(), eventData.c_str());
1706     Want want;
1707     want.SetAction(eventData);
1708     ElementName element;
1709     element.SetBundleName(bundleName);
1710     want.SetElement(element);
1711     want.SetParam(Constants::USER_ID, 0);
1712     EventFwk::CommonEventData commonData {want};
1713     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1714 }
1715 
NotifyAppStatusByCallerUid(const std::string & bundleName,const int32_t userId,const int32_t callerUid,const std::string & eventData)1716 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t userId,
1717     const int32_t callerUid, const std::string &eventData)
1718 {
1719     HILOG_INFO("%{public}s called, bundle name is %{public}s, , userId is %{public}d, event is %{public}s",
1720         __func__, bundleName.c_str(), userId, eventData.c_str());
1721     Want want;
1722     want.SetAction(eventData);
1723     ElementName element;
1724     element.SetBundleName(bundleName);
1725     want.SetElement(element);
1726     want.SetParam(Constants::USER_ID, userId);
1727     want.SetParam(Constants::UID, callerUid);
1728     EventFwk::CommonEventData commonData {want};
1729     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
1730 }
1731 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)1732 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
1733 {
1734     HILOG_INFO("%{public}s begin", __func__);
1735     if (VerifyObserverPermission() == ERR_PERMISSION_DENIED) {
1736         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1737         return ERR_PERMISSION_DENIED;
1738     }
1739     std::lock_guard<std::recursive_mutex> lockRegister(observerLock_);
1740     if (observer == nullptr) {
1741         HILOG_ERROR("Observer nullptr");
1742         return ERR_INVALID_VALUE;
1743     }
1744     if (ObserverExist(observer)) {
1745         HILOG_ERROR("Observer exist.");
1746         return ERR_INVALID_VALUE;
1747     }
1748     appStateObservers_.push_back(observer);
1749     HILOG_INFO("%{public}s appStateObservers_ size:%{public}d", __func__, (int32_t)appStateObservers_.size());
1750     AddObserverDeathRecipient(observer);
1751     return ERR_OK;
1752 }
1753 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)1754 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
1755 {
1756     HILOG_INFO("%{public}s begin", __func__);
1757     if (VerifyObserverPermission() == ERR_PERMISSION_DENIED) {
1758         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1759         return ERR_PERMISSION_DENIED;
1760     }
1761     std::lock_guard<std::recursive_mutex> lockUnregister(observerLock_);
1762     if (observer == nullptr) {
1763         HILOG_ERROR("Observer nullptr");
1764         return ERR_INVALID_VALUE;
1765     }
1766     std::vector<sptr<IApplicationStateObserver>>::iterator it;
1767     for (it = appStateObservers_.begin(); it != appStateObservers_.end(); ++it) {
1768         if ((*it)->AsObject() == observer->AsObject()) {
1769             appStateObservers_.erase(it);
1770             HILOG_INFO("%{public}s appStateObservers_ size:%{public}d", __func__, (int32_t)appStateObservers_.size());
1771             RemoveObserverDeathRecipient(observer);
1772             return ERR_OK;
1773         }
1774     }
1775     HILOG_ERROR("Observer not exist.");
1776     return ERR_INVALID_VALUE;
1777 }
1778 
ObserverExist(const sptr<IApplicationStateObserver> & observer)1779 bool AppMgrServiceInner::ObserverExist(const sptr<IApplicationStateObserver> &observer)
1780 {
1781     if (observer == nullptr) {
1782         HILOG_ERROR("Observer nullptr");
1783         return false;
1784     }
1785     for (int i = 0; i < (int)appStateObservers_.size(); i++) {
1786         if (appStateObservers_[i]->AsObject() == observer->AsObject()) {
1787             return true;
1788         }
1789     }
1790     return false;
1791 }
1792 
AddObserverDeathRecipient(const sptr<IApplicationStateObserver> & observer)1793 void AppMgrServiceInner::AddObserverDeathRecipient(const sptr<IApplicationStateObserver> &observer)
1794 {
1795     HILOG_INFO("%{public}s begin", __func__);
1796     if (observer == nullptr || observer->AsObject() == nullptr) {
1797         HILOG_ERROR("observer nullptr.");
1798         return;
1799     }
1800     auto it = recipientMap_.find(observer->AsObject());
1801     if (it != recipientMap_.end()) {
1802         HILOG_ERROR("This death recipient has been added.");
1803         return;
1804     } else {
1805         sptr<IRemoteObject::DeathRecipient> deathRecipient = new ApplicationStateObserverRecipient(
1806             std::bind(&AppMgrServiceInner::OnObserverDied, this, std::placeholders::_1));
1807         observer->AsObject()->AddDeathRecipient(deathRecipient);
1808         recipientMap_.emplace(observer->AsObject(), deathRecipient);
1809     }
1810 }
1811 
RemoveObserverDeathRecipient(const sptr<IApplicationStateObserver> & observer)1812 void AppMgrServiceInner::RemoveObserverDeathRecipient(const sptr<IApplicationStateObserver> &observer)
1813 {
1814     HILOG_INFO("%{public}s begin", __func__);
1815     if (observer == nullptr || observer->AsObject() == nullptr) {
1816         HILOG_ERROR("observer nullptr.");
1817         return;
1818     }
1819     auto it = recipientMap_.find(observer->AsObject());
1820     if (it != recipientMap_.end()) {
1821         it->first->RemoveDeathRecipient(it->second);
1822         recipientMap_.erase(it);
1823         return;
1824     }
1825 }
1826 
OnObserverDied(const wptr<IRemoteObject> & remote)1827 void AppMgrServiceInner::OnObserverDied(const wptr<IRemoteObject> &remote)
1828 {
1829     HILOG_INFO("%{public}s begin", __func__);
1830     auto object = remote.promote();
1831     if (object == nullptr) {
1832         HILOG_ERROR("observer nullptr.");
1833         return;
1834     }
1835     if (eventHandler_) {
1836         auto task = [object, appManager = this]() {appManager->HandleObserverDiedTask(object);};
1837         eventHandler_->PostTask(task, TASK_ON_CALLBACK_DIED);
1838     }
1839 }
1840 
HandleObserverDiedTask(const sptr<IRemoteObject> & observer)1841 void AppMgrServiceInner::HandleObserverDiedTask(const sptr<IRemoteObject> &observer)
1842 {
1843     HILOG_INFO("Handle call back died task.");
1844     if (observer == nullptr) {
1845         HILOG_ERROR("observer nullptr.");
1846         return;
1847     }
1848     sptr<IApplicationStateObserver> object = iface_cast<IApplicationStateObserver>(observer);
1849     UnregisterApplicationStateObserver(object);
1850 }
1851 
GetForegroundApplications(std::vector<AppStateData> & list)1852 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
1853 {
1854     HILOG_INFO("%{public}s, begin.", __func__);
1855     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1856     if (!isPerm) {
1857         HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1858         return ERR_PERMISSION_DENIED;
1859     }
1860 
1861     appRunningManager_->GetForegroundApplications(list);
1862     return ERR_OK;
1863 }
1864 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)1865 int AppMgrServiceInner::StartUserTestProcess(
1866     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
1867 {
1868     HILOG_INFO("Enter");
1869     if (!observer) {
1870         HILOG_ERROR("observer nullptr.");
1871         return ERR_INVALID_VALUE;
1872     }
1873     if (!appRunningManager_) {
1874         HILOG_ERROR("appRunningManager_ is nullptr");
1875         return ERR_INVALID_VALUE;
1876     }
1877 
1878     std::string bundleName = want.GetStringParam("-b");
1879     if (bundleName.empty()) {
1880         HILOG_ERROR("Invalid bundle name");
1881         return ERR_INVALID_VALUE;
1882     }
1883 
1884     if (KillApplicationByUserIdLocked(bundleName, userId)) {
1885         HILOG_ERROR("Failed to kill the application");
1886         return ERR_INVALID_VALUE;
1887     }
1888 
1889     HapModuleInfo hapModuleInfo;
1890     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
1891         HILOG_ERROR("Failed to get HapModuleInfo for TestRunner");
1892         return ERR_INVALID_VALUE;
1893     }
1894 
1895     std::string processName;
1896     MakeProcessName(processName, std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo);
1897     HILOG_INFO("processName = [%{public}s]", processName.c_str());
1898 
1899     // Inspection records
1900     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
1901         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
1902     if (appRecord) {
1903         HILOG_INFO("processName [%{public}s] Already exists ", processName.c_str());
1904         return ERR_INVALID_VALUE;
1905     }
1906 
1907     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
1908 }
1909 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)1910 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
1911     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
1912 {
1913     HILOG_INFO("Enter");
1914     if (!observer) {
1915         HILOG_ERROR("observer nullptr.");
1916         return ERR_INVALID_VALUE;
1917     }
1918 
1919     bool moduelJson = false;
1920     if (!bundleInfo.hapModuleInfos.empty()) {
1921         moduelJson = bundleInfo.hapModuleInfos.back().isModuleJson;
1922     }
1923     if (moduelJson) {
1924         std::string moudleName = want.GetStringParam("-m");
1925         if (moudleName.empty()) {
1926             UserTestAbnormalFinish(observer, "No module name is specified.");
1927             return ERR_INVALID_VALUE;
1928         }
1929 
1930         bool found = false;
1931         for (auto item : bundleInfo.hapModuleInfos) {
1932             if (item.moduleName == moudleName) {
1933                 hapModuleInfo = item;
1934                 found = true;
1935                 break;
1936             }
1937         }
1938         if (!found) {
1939             UserTestAbnormalFinish(observer, "The specified module name is not found.");
1940             return ERR_INVALID_VALUE;
1941         }
1942     }
1943     return ERR_OK;
1944 }
1945 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)1946 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
1947 {
1948     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
1949     if (!observerProxy) {
1950         HILOG_ERROR("Failed to get ITestObserver proxy");
1951         return ERR_INVALID_VALUE;
1952     }
1953     observerProxy->TestFinished(msg, -1);
1954     return ERR_OK;
1955 }
1956 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)1957 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
1958     const BundleInfo &info, const std::string &processName, const int userId)
1959 {
1960     HILOG_INFO("enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(), processName.c_str());
1961     if (!CheckRemoteClient() || !appRunningManager_) {
1962         HILOG_ERROR("Failed to start the process being tested!");
1963         return ERR_INVALID_VALUE;
1964     }
1965 
1966     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
1967     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
1968     if (!appRecord) {
1969         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
1970         return ERR_INVALID_VALUE;
1971     }
1972 
1973     auto isDebug = want.GetBoolParam("debugApp", false);
1974     HILOG_INFO("Set Debug : %{public}s", (isDebug ? "true" : "false"));
1975     appRecord->SetDebugApp(isDebug);
1976 
1977     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
1978     if (!testRecord) {
1979         HILOG_ERROR("Failed to make UserTestRecord!");
1980         return ERR_INVALID_VALUE;
1981     }
1982     testRecord->want = want;
1983     testRecord->observer = observer;
1984     testRecord->isFinished = false;
1985     testRecord->userId = userId;
1986     appRecord->SetUserTestInfo(testRecord);
1987 
1988     StartProcess(appInfo->name, processName, false, appRecord, appInfo->uid, appInfo->bundleName);
1989 
1990     // If it is empty, the startup failed
1991     if (!appRecord) {
1992         HILOG_ERROR("Failed to start process [%{public}s]!", processName.c_str());
1993         return ERR_INVALID_VALUE;
1994     }
1995 
1996     appRecord->SetEventHandler(eventHandler_);
1997     appRecord->AddModules(appInfo, info.hapModuleInfos);
1998     HILOG_INFO("StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid());
1999 
2000     return ERR_OK;
2001 }
2002 
FinishUserTest(const std::string & msg,const int & resultCode,const std::string & bundleName,const pid_t & pid)2003 int AppMgrServiceInner::FinishUserTest(
2004     const std::string &msg, const int &resultCode, const std::string &bundleName, const pid_t &pid)
2005 {
2006     HILOG_INFO("Enter");
2007     if (bundleName.empty()) {
2008         HILOG_ERROR("Invalid bundle name.");
2009         return ERR_INVALID_VALUE;
2010     }
2011     auto appRecord = GetAppRunningRecordByPid(pid);
2012     if (!appRecord) {
2013         HILOG_ERROR("no such appRecord");
2014         return ERR_INVALID_VALUE;
2015     }
2016 
2017     auto userTestRecord = appRecord->GetUserTestInfo();
2018     if (!userTestRecord) {
2019         HILOG_ERROR("unstart user test");
2020         return ERR_INVALID_VALUE;
2021     }
2022 
2023     FinishUserTestLocked(msg, resultCode, appRecord);
2024 
2025     int ret = KillApplicationByUserIdLocked(bundleName, userTestRecord->userId);
2026     if (ret) {
2027         HILOG_ERROR("Failed to kill process.");
2028         return ret;
2029     }
2030 
2031     return ERR_OK;
2032 }
2033 
FinishUserTestLocked(const std::string & msg,const int & resultCode,std::shared_ptr<AppRunningRecord> & appRecord)2034 int AppMgrServiceInner::FinishUserTestLocked(
2035     const std::string &msg, const int &resultCode, std::shared_ptr<AppRunningRecord> &appRecord)
2036 {
2037     HILOG_INFO("Enter");
2038     if (!appRecord) {
2039         HILOG_ERROR("Invalid appRecord");
2040         return ERR_INVALID_VALUE;
2041     }
2042 
2043     std::unique_lock<std::mutex> lck(userTestLock_);
2044     auto userTestRecord = appRecord->GetUserTestInfo();
2045     if (!userTestRecord) {
2046         HILOG_WARN("unstart user test");
2047         return ERR_INVALID_VALUE;
2048     }
2049     if (!userTestRecord->isFinished) {
2050         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
2051         if (!observerProxy) {
2052             HILOG_ERROR("Failed to get ITestObserver proxy");
2053             return ERR_INVALID_VALUE;
2054         }
2055         observerProxy->TestFinished(msg, resultCode);
2056 
2057         userTestRecord->isFinished = true;
2058     }
2059 
2060     return ERR_OK;
2061 }
2062 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo)2063 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo)
2064 {
2065     HILOG_DEBUG("Start specified ability.");
2066     if (!CheckRemoteClient()) {
2067         return;
2068     }
2069 
2070     BundleInfo bundleInfo;
2071     HapModuleInfo hapModuleInfo;
2072     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
2073     if (!appInfo) {
2074         HILOG_ERROR("appInfo is nullptr.");
2075         return;
2076     }
2077 
2078     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo)) {
2079         return;
2080     }
2081 
2082     std::string processName;
2083     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
2084     if (!abilityInfoPtr) {
2085         HILOG_ERROR("abilityInfoPtr is nullptr.");
2086         return;
2087     }
2088     MakeProcessName(processName, abilityInfoPtr, appInfo, hapModuleInfo);
2089 
2090     std::vector<HapModuleInfo> hapModules;
2091     hapModules.emplace_back(hapModuleInfo);
2092 
2093     std::shared_ptr<AppRunningRecord> appRecord;
2094     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
2095     if (!appRecord) {
2096         // new app record
2097         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
2098         if (!appRecord) {
2099             HILOG_ERROR("start process [%{public}s] failed!", processName.c_str());
2100             return;
2101         }
2102         appRecord->SetEventHandler(eventHandler_);
2103         appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
2104             AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT);
2105         bool coldStart = want.GetBoolParam("coldStart", false);
2106         StartProcess(appInfo->name, processName, coldStart, appRecord, appInfo->uid, appInfo->bundleName);
2107 
2108         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2109         appRecord->AddModules(appInfo, hapModules);
2110     } else {
2111         HILOG_DEBUG("process is exist");
2112         appRecord->SetSpecifiedAbilityFlagAndWant(true, want, hapModuleInfo.moduleName);
2113         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
2114         if (!moduleRecord) {
2115             HILOG_DEBUG("module record is nullptr, add modules");
2116             appRecord->AddModules(appInfo, hapModules);
2117             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
2118         } else {
2119             HILOG_DEBUG("schedule accept want");
2120             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
2121         }
2122     }
2123 }
2124 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)2125 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
2126 {
2127     if (!response) {
2128         HILOG_ERROR("response is nullptr, register failed.");
2129         return;
2130     }
2131 
2132     pid_t callingPid = IPCSkeleton::GetCallingPid();
2133     pid_t pid = getpid();
2134     if (callingPid != pid) {
2135         HILOG_ERROR("%{public}s: Not abilityMgr call.", __func__);
2136         return;
2137     }
2138 
2139     startSpecifiedAbilityResponse_ = response;
2140 }
2141 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)2142 void AppMgrServiceInner::ScheduleAcceptWantDone(
2143     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
2144 {
2145     HILOG_DEBUG("Schedule accept want done, flag: %{public}s", flag.c_str());
2146 
2147     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
2148     if (!appRecord) {
2149         HILOG_ERROR("Get app record failed.");
2150         return;
2151     }
2152     appRecord->ScheduleAcceptWantDone();
2153 
2154     if (startSpecifiedAbilityResponse_) {
2155         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag);
2156     }
2157 }
2158 
HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)2159 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)
2160 {
2161     HILOG_DEBUG("called start specified ability time out!");
2162     if (!appRunningManager_) {
2163         HILOG_ERROR("appRunningManager_ is nullptr");
2164         return;
2165     }
2166 
2167     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2168     if (!appRecord) {
2169         HILOG_ERROR("appRecord is nullptr");
2170         return;
2171     }
2172 
2173     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
2174         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant());
2175     }
2176 
2177     KillApplicationByRecord(appRecord);
2178 }
2179 
UpdateConfiguration(const Configuration & config)2180 void AppMgrServiceInner::UpdateConfiguration(const Configuration &config)
2181 {
2182     if (!appRunningManager_) {
2183         HILOG_ERROR("appRunningManager_ is null");
2184         return;
2185     }
2186 
2187     std::vector<std::string> changeKeyV;
2188     configuration_->CompareDifferent(changeKeyV, config);
2189     uint32_t size = changeKeyV.size();
2190     HILOG_INFO("changeKeyV size :%{public}u", size);
2191     if (!changeKeyV.empty()) {
2192         configuration_->Merge(changeKeyV, config);
2193         // all app
2194         appRunningManager_->UpdateConfiguration(config);
2195     }
2196 }
2197 
GetGlobalConfiguration()2198 void AppMgrServiceInner::GetGlobalConfiguration()
2199 {
2200     if (!configuration_) {
2201         HILOG_ERROR("configuration_ is null");
2202         return;
2203     }
2204 
2205 #ifdef SUPPORT_GRAPHICS
2206     // Currently only this interface is known
2207     auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLanguage();
2208     HILOG_INFO("current global language is : %{public}s", language.c_str());
2209     configuration_->AddItem(GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
2210 #endif
2211 
2212     // Assign to default colormode "light"
2213     HILOG_INFO("current global colormode is : %{public}s", ConfigurationInner::COLOR_MODE_LIGHT.c_str());
2214     configuration_->AddItem(GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
2215 }
2216 
GetConfiguration()2217 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
2218 {
2219     return configuration_;
2220 }
2221 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)2222 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
2223 {
2224     HILOG_DEBUG("Kill application by appRecord.");
2225 
2226     if (!appRecord) {
2227         HILOG_DEBUG("appRecord is nullptr.");
2228         return;
2229     }
2230 
2231     auto pid = appRecord->GetPriorityObject()->GetPid();
2232     appRecord->SetTerminating();
2233     appRecord->ScheduleProcessSecurityExit();
2234 
2235     auto startTime = SystemTimeMillis();
2236     std::list<pid_t> pids = {pid};
2237     if (WaitForRemoteProcessExit(pids, startTime)) {
2238         HILOG_DEBUG("The remote process exited successfully");
2239         return;
2240     }
2241 
2242     auto result = KillProcessByPid(pid);
2243     if (result < 0) {
2244         HILOG_ERROR("Kill application by app record, pid: %{public}d", pid);
2245     }
2246 }
2247 
SendHiSysEvent(const int32_t innerEventId,const int64_t eventId)2248 void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_t eventId)
2249 {
2250     HILOG_DEBUG("called AppMgrServiceInner SendHiSysEvent!");
2251     if (!appRunningManager_) {
2252         HILOG_ERROR("appRunningManager_ is nullptr");
2253         return;
2254     }
2255 
2256     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
2257     if (!appRecord) {
2258         HILOG_ERROR("appRecord is nullptr");
2259         return;
2260     }
2261 
2262     std::string eventName = EVENT_NAME_LIFECYCLE_TIMEOUT;
2263     std::string pidStr = std::to_string(appRecord->GetPriorityObject()->GetPid());
2264     std::string uidStr = std::to_string(appRecord->GetUid());
2265     std::string packageName = appRecord->GetBundleName();
2266     std::string processName = appRecord->GetProcessName();
2267     std::string msg;
2268     switch (innerEventId) {
2269         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
2270             msg = EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
2271             break;
2272         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
2273             msg = EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
2274             break;
2275         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
2276             msg = EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
2277             break;
2278         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
2279             msg = EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
2280             break;
2281         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
2282             msg = EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
2283             break;
2284         default:
2285             msg = EVENT_MESSAGE_DEFAULT;
2286             break;
2287     }
2288 
2289     HILOG_DEBUG("SendHiSysEvent, eventName = %{public}s, uidStr = %{public}s, pidStr = %{public}s, \
2290         packageName = %{public}s, processName = %{public}s, msg = %{public}s",
2291         eventName.c_str(),
2292         uidStr.c_str(),
2293         pidStr.c_str(),
2294         packageName.c_str(),
2295         processName.c_str(),
2296         msg.c_str());
2297 
2298     OHOS::HiviewDFX::HiSysEvent::Write(
2299         OHOS::HiviewDFX::HiSysEvent::Domain::AAFWK,
2300         eventName,
2301         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
2302         EVENT_KEY_PID, pidStr,
2303         EVENT_KEY_UID, uidStr,
2304         EVENT_KEY_PACKAGE_NAME, packageName,
2305         EVENT_KEY_PROCESS_NAME, processName,
2306         EVENT_KEY_MESSAGE, msg);
2307 }
2308 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)2309 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
2310 {
2311     auto appRecord = GetAppRunningRecordByPid(pid);
2312     if (!appRecord) {
2313         HILOG_ERROR("no such appRecord");
2314         return ERR_NAME_NOT_FOUND;
2315     }
2316     for (auto &item : appRecord->GetAbilities()) {
2317         tokens.emplace_back(item.first);
2318     }
2319     return ERR_OK;
2320 }
2321 
VerifyProcessPermission()2322 int AppMgrServiceInner::VerifyProcessPermission()
2323 {
2324     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2325     if (isSaCall) {
2326         return ERR_OK;
2327     }
2328 
2329     if (!appRunningManager_) {
2330         HILOG_ERROR("appRunningManager_ is nullptr");
2331         return ERR_NO_INIT;
2332     }
2333 
2334     auto callerPid = IPCSkeleton::GetCallingPid();
2335     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
2336     if (!appRecord) {
2337         HILOG_ERROR("Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
2338         return ERR_INVALID_OPERATION;
2339     }
2340 
2341     auto applicationInfo = appRecord->GetApplicationInfo();
2342     if (!applicationInfo) {
2343         HILOG_ERROR("Get application info failed.");
2344         return ERR_INVALID_OPERATION;
2345     }
2346 
2347     auto apl = applicationInfo->appPrivilegeLevel;
2348     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
2349         HILOG_ERROR("caller is not system_basic or system_core.");
2350         return ERR_INVALID_OPERATION;
2351     }
2352 
2353     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2354         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
2355     if (isCallingPerm) {
2356         HILOG_ERROR("%{public}s: Permission verification succeeded", __func__);
2357         return ERR_OK;
2358     }
2359     HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2360     return ERR_PERMISSION_DENIED;
2361 }
2362 
VerifyAccountPermission(const std::string & permissionName,const int userId)2363 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId)
2364 {
2365     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2366     if (isSaCall) {
2367         return ERR_OK;
2368     }
2369 
2370     const int currentUserId = (int)(getuid() / Constants::BASE_USER_RANGE);
2371     if (userId != currentUserId) {
2372         auto isCallingPermAccount = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2373             AAFwk::PermissionConstants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
2374         if (!isCallingPermAccount) {
2375             HILOG_ERROR("%{public}s: Permission accounts verification failed", __func__);
2376             return ERR_PERMISSION_DENIED;
2377         }
2378     }
2379     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(permissionName);
2380     if (isCallingPerm) {
2381         HILOG_DEBUG("%{public}s: Permission verification succeeded", __func__);
2382         return ERR_OK;
2383     }
2384     HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2385     return ERR_PERMISSION_DENIED;
2386 }
2387 
VerifyObserverPermission()2388 int AppMgrServiceInner::VerifyObserverPermission()
2389 {
2390     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2391     if (isSaCall) {
2392         return ERR_OK;
2393     }
2394     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2395         AAFwk::PermissionConstants::PERMISSION_RUNNING_STATE_OBSERVER);
2396     if (isCallingPerm) {
2397         HILOG_ERROR("%{public}s: Permission verification succeeded", __func__);
2398         return ERR_OK;
2399     }
2400     HILOG_ERROR("%{public}s: Permission verification failed", __func__);
2401     return ERR_PERMISSION_DENIED;
2402 }
2403 
StartRenderProcess(const pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,pid_t & renderPid)2404 int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam,
2405     int32_t ipcFd, int32_t sharedFd, pid_t &renderPid)
2406 {
2407     HILOG_INFO("start render process, nweb hostpid:%{public}d", hostPid);
2408     if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0) {
2409         HILOG_ERROR("invalid param, hostPid:%{public}d, renderParam:%{public}s, ipcFd:%{public}d, sharedFd:%{public}d",
2410             hostPid, renderParam.c_str(), ipcFd, sharedFd);
2411         return ERR_INVALID_VALUE;
2412     }
2413 
2414     if (!appRunningManager_) {
2415         HILOG_ERROR("appRunningManager_ is , not start render process");
2416         return ERR_INVALID_VALUE;
2417     }
2418 
2419     auto appRecord = GetAppRunningRecordByPid(hostPid);
2420     if (!appRecord) {
2421         HILOG_ERROR("no such appRecord, hostpid:%{public}d", hostPid);
2422         return ERR_INVALID_VALUE;
2423     }
2424 
2425     auto renderRecord = appRecord->GetRenderRecord();
2426     if (renderRecord) {
2427         HILOG_WARN("already exit render process,do not request again, renderPid:%{public}d", renderRecord->GetPid());
2428         renderPid = renderRecord->GetPid();
2429         return ERR_ALREADY_EXIST_RENDER;
2430     }
2431 
2432     renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam, ipcFd, sharedFd, appRecord);
2433     if (!renderRecord) {
2434         HILOG_ERROR("create render record failed, hostpid:%{public}d", hostPid);
2435         return ERR_INVALID_VALUE;
2436     }
2437 
2438     return StartRenderProcessImpl(renderRecord, appRecord, renderPid);
2439 }
2440 
AttachRenderProcess(const pid_t pid,const sptr<IRenderScheduler> & scheduler)2441 void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler)
2442 {
2443     HILOG_DEBUG("attach render process start");
2444     if (pid <= 0) {
2445         HILOG_ERROR("invalid render process pid:%{public}d", pid);
2446         return;
2447     }
2448     if (!scheduler) {
2449         HILOG_ERROR("render scheduler is null");
2450         return;
2451     }
2452 
2453     if (!appRunningManager_) {
2454         HILOG_ERROR("appRunningManager_ is null");
2455         return;
2456     }
2457 
2458     HILOG_INFO("attach render process pid:%{public}d", pid);
2459     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
2460     if (!appRecord) {
2461         HILOG_ERROR("no such app Record, pid:%{public}d", pid);
2462         return;
2463     }
2464 
2465     auto renderRecord = appRecord->GetRenderRecord();
2466     if (!renderRecord) {
2467         HILOG_ERROR("no such render Record, pid:%{public}d", pid);
2468         return;
2469     }
2470 
2471     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
2472     appDeathRecipient->SetEventHandler(eventHandler_);
2473     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
2474     appDeathRecipient->SetIsRenderProcess(true);
2475     renderRecord->SetScheduler(scheduler);
2476     renderRecord->SetDeathRecipient(appDeathRecipient);
2477     renderRecord->RegisterDeathRecipient();
2478 
2479     // notify fd to render process
2480     scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(), renderRecord->GetSharedFd());
2481 }
2482 
StartRenderProcessImpl(const std::shared_ptr<RenderRecord> & renderRecord,const std::shared_ptr<AppRunningRecord> appRecord,pid_t & renderPid)2483 int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
2484     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid)
2485 {
2486     if (!renderRecord || !appRecord) {
2487         HILOG_ERROR("renderRecord or appRecord is nullptr.");
2488         return ERR_INVALID_VALUE;
2489     }
2490 
2491     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
2492     if (!nwebSpawnClient) {
2493         HILOG_ERROR("nwebSpawnClient is null");
2494         return ERR_INVALID_VALUE;
2495     }
2496 
2497     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
2498     startMsg.renderParam = renderRecord->GetRenderParam();
2499     startMsg.code = 0; // 0: DEFAULT
2500     pid_t pid = 0;
2501     ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid);
2502     if (FAILED(errCode)) {
2503         HILOG_ERROR("failed to spawn new render process, errCode %{public}08x", errCode);
2504         return ERR_INVALID_VALUE;
2505     }
2506     renderPid = pid;
2507     appRecord->SetRenderRecord(renderRecord);
2508     renderRecord->SetPid(pid);
2509     HILOG_INFO("start render process successed, hostPid:%{public}d, pid:%{public}d uid:%{public}d",
2510         renderRecord->GetHostPid(), pid, startMsg.uid);
2511     return 0;
2512 }
2513 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)2514 int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
2515 {
2516     if (remoteClientManager_ == nullptr) {
2517         HILOG_ERROR("remoteClientManager_ is null");
2518         return ERR_INVALID_VALUE;
2519     }
2520     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
2521     if (!nwebSpawnClient) {
2522         HILOG_ERROR("nwebSpawnClient is null");
2523         return ERR_INVALID_VALUE;
2524     }
2525 
2526     AppSpawnStartMsg startMsg;
2527     startMsg.pid = renderPid;
2528     startMsg.code = 1; // 1: GET_RENDER_TERMINATION_STATUS
2529     ErrCode errCode = nwebSpawnClient->GetRenderProcessTerminationStatus(startMsg, status);
2530     if (FAILED(errCode)) {
2531         HILOG_ERROR("failed to get render process termination status, errCode %{public}08x", errCode);
2532         return ERR_INVALID_VALUE;
2533     }
2534     HILOG_INFO("Get render process termination status successed, renderPid:%{public}d, status:%{public}d",
2535         renderPid, status);
2536     return 0;
2537 }
2538 
OnRenderRemoteDied(const wptr<IRemoteObject> & remote)2539 void AppMgrServiceInner::OnRenderRemoteDied(const wptr<IRemoteObject> &remote)
2540 {
2541     HILOG_ERROR("On render remote died.");
2542     if (appRunningManager_) {
2543         appRunningManager_->OnRemoteRenderDied(remote);
2544     }
2545 }
2546 }  // namespace AppExecFwk
2547 }  // namespace OHOS
2548