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