1 /*
2 * Copyright (c) 2021-2024 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_running_manager.h"
17
18 #include "app_mgr_service_inner.h"
19 #include "datetime_ex.h"
20 #include "iremote_object.h"
21
22 #include "appexecfwk_errors.h"
23 #include "app_utils.h"
24 #include "common_event_support.h"
25 #include "exit_resident_process_manager.h"
26 #include "freeze_util.h"
27 #include "hilog_tag_wrapper.h"
28 #include "hitrace_meter.h"
29 #include "os_account_manager_wrapper.h"
30 #include "perf_profile.h"
31 #include "parameters.h"
32 #include "quick_fix_callback_with_record.h"
33 #include <cstddef>
34 #include "scene_board_judgement.h"
35 #include "app_mgr_service_const.h"
36 #include "app_mgr_service_dump_error_code.h"
37 #include "window_visibility_info.h"
38 #include "cache_process_manager.h"
39 #include "res_sched_util.h"
40 #include "ui_extension_utils.h"
41 #include "uri_permission_manager_client.h"
42 namespace OHOS {
43 namespace AppExecFwk {
44 namespace {
45 constexpr int32_t QUICKFIX_UID = 5524;
46 const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant";
47 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
48 }
49 using EventFwk::CommonEventSupport;
50
AppRunningManager()51 AppRunningManager::AppRunningManager()
52 : configuration_(std::make_shared<Configuration>())
53 {}
~AppRunningManager()54 AppRunningManager::~AppRunningManager()
55 {}
56
initConfig(const Configuration & config)57 void AppRunningManager::initConfig(const Configuration &config)
58 {
59 std::vector<std::string> changeKeyV;
60 configuration_->CompareDifferent(changeKeyV, config);
61 if (!changeKeyV.empty()) {
62 configuration_->Merge(changeKeyV, config);
63 }
64 }
65
CreateAppRunningRecord(const std::shared_ptr<ApplicationInfo> & appInfo,const std::string & processName,const BundleInfo & bundleInfo)66 std::shared_ptr<AppRunningRecord> AppRunningManager::CreateAppRunningRecord(
67 const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName, const BundleInfo &bundleInfo)
68 {
69 if (!appInfo) {
70 TAG_LOGE(AAFwkTag::APPMGR, "param error");
71 return nullptr;
72 }
73
74 if (processName.empty()) {
75 TAG_LOGE(AAFwkTag::APPMGR, "processName error");
76 return nullptr;
77 }
78
79 auto recordId = AppRecordId::Create();
80 auto appRecord = std::make_shared<AppRunningRecord>(appInfo, recordId, processName);
81
82 std::regex rule("[a-zA-Z.]+[-_#]{1}");
83 std::string signCode;
84 bool isStageBasedModel = false;
85 ClipStringContent(rule, bundleInfo.appId, signCode);
86 if (!bundleInfo.hapModuleInfos.empty()) {
87 isStageBasedModel = bundleInfo.hapModuleInfos.back().isStageBasedModel;
88 }
89 TAG_LOGD(AAFwkTag::APPMGR,
90 "Create AppRunningRecord, processName: %{public}s, StageBasedModel:%{public}d, recordId: %{public}d",
91 processName.c_str(), isStageBasedModel, recordId);
92
93 appRecord->SetStageModelState(isStageBasedModel);
94 appRecord->SetSingleton(bundleInfo.singleton);
95 appRecord->SetKeepAliveBundle(bundleInfo.isKeepAlive);
96 appRecord->SetSignCode(signCode);
97 appRecord->SetJointUserId(bundleInfo.jointUserId);
98 appRecord->SetAppIdentifier(bundleInfo.signatureInfo.appIdentifier);
99 {
100 std::lock_guard guard(runningRecordMapMutex_);
101 appRunningRecordMap_.emplace(recordId, appRecord);
102 }
103 {
104 std::lock_guard guard(updateConfigurationDelayedLock_);
105 updateConfigurationDelayedMap_.emplace(recordId, false);
106 }
107 return appRecord;
108 }
109
CheckAppRunningRecordIsExist(const std::string & appName,const std::string & processName,const int uid,const BundleInfo & bundleInfo,const std::string & specifiedProcessFlag)110 std::shared_ptr<AppRunningRecord> AppRunningManager::CheckAppRunningRecordIsExist(const std::string &appName,
111 const std::string &processName, const int uid, const BundleInfo &bundleInfo,
112 const std::string &specifiedProcessFlag)
113 {
114 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
115 TAG_LOGD(AAFwkTag::APPMGR,
116 "appName: %{public}s, processName: %{public}s, uid: %{public}d, specifiedProcessFlag: %{public}s",
117 appName.c_str(), processName.c_str(), uid, specifiedProcessFlag.c_str());
118 std::regex rule("[a-zA-Z.]+[-_#]{1}");
119 std::string signCode;
120 auto jointUserId = bundleInfo.jointUserId;
121 TAG_LOGD(AAFwkTag::APPMGR, "jointUserId : %{public}s", jointUserId.c_str());
122 ClipStringContent(rule, bundleInfo.appId, signCode);
123
124 auto FindSameProcess = [signCode, specifiedProcessFlag, processName, jointUserId](const auto &pair) {
125 return (pair.second != nullptr) &&
126 (specifiedProcessFlag.empty() ||
127 pair.second->GetSpecifiedProcessFlag() == specifiedProcessFlag) &&
128 (pair.second->GetSignCode() == signCode) &&
129 (pair.second->GetProcessName() == processName) &&
130 (pair.second->GetJointUserId() == jointUserId) &&
131 !(pair.second->IsTerminating()) &&
132 !(pair.second->IsKilling()) && !(pair.second->GetRestartAppFlag());
133 };
134
135 auto appRunningMap = GetAppRunningRecordMap();
136 if (!jointUserId.empty()) {
137 auto iter = std::find_if(appRunningMap.begin(), appRunningMap.end(), FindSameProcess);
138 return ((iter == appRunningMap.end()) ? nullptr : iter->second);
139 }
140 for (const auto &item : appRunningMap) {
141 const auto &appRecord = item.second;
142 if (appRecord && appRecord->GetProcessName() == processName &&
143 (specifiedProcessFlag.empty() ||
144 appRecord->GetSpecifiedProcessFlag() == specifiedProcessFlag) &&
145 !(appRecord->IsTerminating()) && !(appRecord->IsKilling()) && !(appRecord->GetRestartAppFlag()) &&
146 !(appRecord->IsUserRequestCleaning())) {
147 auto appInfoList = appRecord->GetAppInfoList();
148 TAG_LOGD(AAFwkTag::APPMGR,
149 "appInfoList: %{public}zu, processName: %{public}s, specifiedProcessFlag: %{public}s",
150 appInfoList.size(), appRecord->GetProcessName().c_str(), specifiedProcessFlag.c_str());
151 auto isExist = [&appName, &uid](const std::shared_ptr<ApplicationInfo> &appInfo) {
152 TAG_LOGD(AAFwkTag::APPMGR, "appInfo->name: %{public}s", appInfo->name.c_str());
153 return appInfo->name == appName && appInfo->uid == uid;
154 };
155 auto appInfoIter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
156 if (appInfoIter != appInfoList.end()) {
157 DelayedSingleton<CacheProcessManager>::GetInstance()->ReuseCachedProcess(appRecord);
158 return appRecord;
159 }
160 }
161 }
162 return nullptr;
163 }
164
165 #ifdef APP_NO_RESPONSE_DIALOG
CheckAppRunningRecordIsExist(const std::string & bundleName,const std::string & ablityName)166 bool AppRunningManager::CheckAppRunningRecordIsExist(const std::string &bundleName, const std::string &ablityName)
167 {
168 std::lock_guard guard(runningRecordMapMutex_);
169 if (appRunningRecordMap_.empty()) {
170 return false;
171 }
172 for (const auto &item : appRunningRecordMap_) {
173 const auto &appRecord = item.second;
174 if (!appRecord) {
175 continue;
176 }
177 if (appRecord->GetBundleName() != bundleName) {
178 continue;
179 }
180 const auto &abilityRunningRecordMap = appRecord->GetAbilities();
181 for (const auto &abilityItem : abilityRunningRecordMap) {
182 const auto &abilityRunning = abilityItem.second;
183 if (abilityRunning && abilityRunning->GetName() == ablityName) {
184 return true;
185 }
186 }
187 }
188 return false;
189 }
190 #endif
191
CheckAppRunningRecordIsExistByBundleName(const std::string & bundleName)192 bool AppRunningManager::CheckAppRunningRecordIsExistByBundleName(const std::string &bundleName)
193 {
194 std::lock_guard guard(runningRecordMapMutex_);
195 if (appRunningRecordMap_.empty()) {
196 return false;
197 }
198 for (const auto &item : appRunningRecordMap_) {
199 const auto &appRecord = item.second;
200 if (appRecord && appRecord->GetBundleName() == bundleName && !(appRecord->GetRestartAppFlag())) {
201 return true;
202 }
203 }
204 return false;
205 }
206
CheckAppRunningRecordIsExistByUid(int32_t uid)207 bool AppRunningManager::CheckAppRunningRecordIsExistByUid(int32_t uid)
208 {
209 std::lock_guard guard(runningRecordMapMutex_);
210 if (appRunningRecordMap_.empty()) {
211 return false;
212 }
213 for (const auto &item : appRunningRecordMap_) {
214 const auto &appRecord = item.second;
215 if (appRecord && appRecord->GetUid() == uid && !(appRecord->GetRestartAppFlag())) {
216 return true;
217 }
218 }
219 return false;
220 }
221
CheckAppCloneRunningRecordIsExistByBundleName(const std::string & bundleName,int32_t appCloneIndex,bool & isRunning)222 int32_t AppRunningManager::CheckAppCloneRunningRecordIsExistByBundleName(const std::string &bundleName,
223 int32_t appCloneIndex, bool &isRunning)
224 {
225 std::lock_guard guard(runningRecordMapMutex_);
226 for (const auto &item : appRunningRecordMap_) {
227 const auto &appRecord = item.second;
228 if (appRecord && appRecord->GetBundleName() == bundleName && !(appRecord->GetRestartAppFlag()) &&
229 appRecord->GetAppIndex() == appCloneIndex) {
230 isRunning = true;
231 break;
232 }
233 }
234 return ERR_OK;
235 }
236
GetAllAppRunningRecordCountByBundleName(const std::string & bundleName)237 int32_t AppRunningManager::GetAllAppRunningRecordCountByBundleName(const std::string &bundleName)
238 {
239 int32_t count = 0;
240 std::lock_guard guard(runningRecordMapMutex_);
241 for (const auto &item : appRunningRecordMap_) {
242 const auto &appRecord = item.second;
243 if (appRecord && appRecord->GetBundleName() == bundleName) {
244 count++;
245 }
246 }
247
248 return count;
249 }
250
GetAppRunningRecordByPid(const pid_t pid)251 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByPid(const pid_t pid)
252 {
253 std::lock_guard guard(runningRecordMapMutex_);
254 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
255 return pair.second->GetPriorityObject()->GetPid() == pid;
256 });
257 return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second);
258 }
259
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken)260 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByAbilityToken(
261 const sptr<IRemoteObject> &abilityToken)
262 {
263 std::lock_guard guard(runningRecordMapMutex_);
264 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
265 for (const auto &item : appRunningRecordMap_) {
266 const auto &appRecord = item.second;
267 if (appRecord && appRecord->GetAbilityRunningRecordByToken(abilityToken)) {
268 return appRecord;
269 }
270 }
271 return nullptr;
272 }
273
ProcessExitByBundleName(const std::string & bundleName,std::list<pid_t> & pids,const bool clearPageStack)274 bool AppRunningManager::ProcessExitByBundleName(const std::string &bundleName, std::list<pid_t> &pids,
275 const bool clearPageStack)
276 {
277 auto appRunningMap = GetAppRunningRecordMap();
278 for (const auto &item : appRunningMap) {
279 const auto &appRecord = item.second;
280 // condition [!appRecord->IsKeepAliveApp()] Is to not kill the resident process.
281 // Before using this method, consider whether you need.
282 if (appRecord && (!appRecord->IsKeepAliveApp() ||
283 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) {
284 pid_t pid = appRecord->GetPriorityObject()->GetPid();
285 auto appInfoList = appRecord->GetAppInfoList();
286 auto isExist = [&bundleName](const std::shared_ptr<ApplicationInfo> &appInfo) {
287 return appInfo->bundleName == bundleName;
288 };
289 auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
290 if (iter == appInfoList.end() || pid <= 0) {
291 continue;
292 }
293 pids.push_back(pid);
294 if (clearPageStack) {
295 appRecord->ScheduleClearPageStack();
296 }
297 appRecord->ScheduleProcessSecurityExit();
298 }
299 }
300
301 return !pids.empty();
302 }
303
GetPidsByUserId(int32_t userId,std::list<pid_t> & pids)304 bool AppRunningManager::GetPidsByUserId(int32_t userId, std::list<pid_t> &pids)
305 {
306 auto appRunningMap = GetAppRunningRecordMap();
307 for (const auto &item : appRunningMap) {
308 const auto &appRecord = item.second;
309 if (appRecord) {
310 int32_t id = -1;
311 if ((DelayedSingleton<OsAccountManagerWrapper>::GetInstance()->
312 GetOsAccountLocalIdFromUid(appRecord->GetUid(), id) == 0) && (id == userId)) {
313 pid_t pid = appRecord->GetPriorityObject()->GetPid();
314 if (pid > 0) {
315 pids.push_back(pid);
316 appRecord->ScheduleProcessSecurityExit();
317 }
318 }
319 }
320 }
321
322 return (!pids.empty());
323 }
324
ProcessUpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)325 int32_t AppRunningManager::ProcessUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
326 {
327 auto appRunningMap = GetAppRunningRecordMap();
328 int32_t result = ERR_OK;
329 for (const auto &item : appRunningMap) {
330 const auto &appRecord = item.second;
331 if (!appRecord) {
332 continue;
333 }
334 auto appInfoList = appRecord->GetAppInfoList();
335 for (auto iter : appInfoList) {
336 if (iter->bundleName == appInfo.bundleName && iter->uid == appInfo.uid) {
337 appRecord->UpdateApplicationInfoInstalled(appInfo);
338 break;
339 }
340 }
341 }
342 return result;
343 }
344
ProcessExitByBundleNameAndUid(const std::string & bundleName,const int uid,std::list<pid_t> & pids,const bool clearPageStack)345 bool AppRunningManager::ProcessExitByBundleNameAndUid(
346 const std::string &bundleName, const int uid, std::list<pid_t> &pids, const bool clearPageStack)
347 {
348 auto appRunningMap = GetAppRunningRecordMap();
349 for (const auto &item : appRunningMap) {
350 const auto &appRecord = item.second;
351 if (appRecord == nullptr) {
352 continue;
353 }
354 auto appInfoList = appRecord->GetAppInfoList();
355 auto isExist = [&bundleName, &uid](const std::shared_ptr<ApplicationInfo> &appInfo) {
356 return appInfo->bundleName == bundleName && appInfo->uid == uid;
357 };
358 auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
359 pid_t pid = appRecord->GetPriorityObject()->GetPid();
360 if (iter == appInfoList.end() || pid <= 0) {
361 continue;
362 }
363 pids.push_back(pid);
364 if (clearPageStack) {
365 appRecord->ScheduleClearPageStack();
366 }
367 appRecord->SetKilling();
368 appRecord->ScheduleProcessSecurityExit();
369 }
370
371 return (pids.empty() ? false : true);
372 }
373
GetPidsByBundleNameUserIdAndAppIndex(const std::string & bundleName,const int userId,const int appIndex,std::list<pid_t> & pids)374 bool AppRunningManager::GetPidsByBundleNameUserIdAndAppIndex(const std::string &bundleName,
375 const int userId, const int appIndex, std::list<pid_t> &pids)
376 {
377 auto appRunningMap = GetAppRunningRecordMap();
378 for (const auto &item : appRunningMap) {
379 const auto &appRecord = item.second;
380 if (appRecord == nullptr) {
381 continue;
382 }
383 auto appInfoList = appRecord->GetAppInfoList();
384 auto isExist = [&bundleName, &userId, &appIndex](const std::shared_ptr<ApplicationInfo> &appInfo) {
385 return appInfo->bundleName == bundleName && appInfo->uid / BASE_USER_RANGE == userId &&
386 appInfo->appIndex == appIndex;
387 };
388 auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
389 pid_t pid = appRecord->GetPriorityObject()->GetPid();
390 if (iter == appInfoList.end() || pid <= 0) {
391 continue;
392 }
393 pids.push_back(pid);
394 appRecord->SetKilling();
395 }
396
397 return (!pids.empty());
398 }
399
OnRemoteDied(const wptr<IRemoteObject> & remote,std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)400 std::shared_ptr<AppRunningRecord> AppRunningManager::OnRemoteDied(const wptr<IRemoteObject> &remote,
401 std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)
402 {
403 TAG_LOGD(AAFwkTag::APPMGR, "called");
404 if (remote == nullptr) {
405 TAG_LOGE(AAFwkTag::APPMGR, "null remote");
406 return nullptr;
407 }
408 sptr<IRemoteObject> object = remote.promote();
409 if (!object) {
410 TAG_LOGE(AAFwkTag::APPMGR, "null object");
411 return nullptr;
412 }
413
414 std::shared_ptr<AppRunningRecord> appRecord = nullptr;
415 {
416 std::lock_guard guard(runningRecordMapMutex_);
417 const auto &iter =
418 std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&object](const auto &pair) {
419 if (pair.second && pair.second->GetApplicationClient() != nullptr) {
420 return pair.second->GetApplicationClient()->AsObject() == object;
421 }
422 return false;
423 });
424 if (iter == appRunningRecordMap_.end()) {
425 TAG_LOGE(AAFwkTag::APPMGR, "remote not in map");
426 return nullptr;
427 }
428 appRecord = iter->second;
429 appRunningRecordMap_.erase(iter);
430 }
431 if (appRecord != nullptr) {
432 {
433 std::lock_guard guard(updateConfigurationDelayedLock_);
434 updateConfigurationDelayedMap_.erase(appRecord->GetRecordId());
435 }
436 appRecord->RemoveAppDeathRecipient();
437 appRecord->SetApplicationClient(nullptr);
438 TAG_LOGI(AAFwkTag::APPMGR, "pname: %{public}s", appRecord->GetProcessName().c_str());
439 auto priorityObject = appRecord->GetPriorityObject();
440 if (priorityObject != nullptr) {
441 TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d", priorityObject->GetPid());
442 if (appMgrServiceInner != nullptr) {
443 appMgrServiceInner->KillProcessByPid(priorityObject->GetPid(), "OnRemoteDied");
444 }
445 AbilityRuntime::FreezeUtil::GetInstance().DeleteAppLifecycleEvent(priorityObject->GetPid());
446 }
447 }
448 if (appRecord != nullptr && appRecord->GetPriorityObject() != nullptr) {
449 RemoveUIExtensionLauncherItem(appRecord->GetPriorityObject()->GetPid());
450 }
451
452 return appRecord;
453 }
454
GetAppRunningRecordMap()455 std::map<const int32_t, const std::shared_ptr<AppRunningRecord>> AppRunningManager::GetAppRunningRecordMap()
456 {
457 std::lock_guard guard(runningRecordMapMutex_);
458 return appRunningRecordMap_;
459 }
460
RemoveAppRunningRecordById(const int32_t recordId)461 void AppRunningManager::RemoveAppRunningRecordById(const int32_t recordId)
462 {
463 std::shared_ptr<AppRunningRecord> appRecord = nullptr;
464 {
465 std::lock_guard guard(runningRecordMapMutex_);
466 auto it = appRunningRecordMap_.find(recordId);
467 if (it != appRunningRecordMap_.end()) {
468 appRecord = it->second;
469 appRunningRecordMap_.erase(it);
470 }
471 }
472 {
473 std::lock_guard guard(updateConfigurationDelayedLock_);
474 updateConfigurationDelayedMap_.erase(recordId);
475 }
476
477 if (appRecord != nullptr && appRecord->GetPriorityObject() != nullptr) {
478 RemoveUIExtensionLauncherItem(appRecord->GetPriorityObject()->GetPid());
479 AbilityRuntime::FreezeUtil::GetInstance().DeleteAppLifecycleEvent(appRecord->GetPriorityObject()->GetPid());
480 }
481 }
482
ClearAppRunningRecordMap()483 void AppRunningManager::ClearAppRunningRecordMap()
484 {
485 std::lock_guard guard(runningRecordMapMutex_);
486 appRunningRecordMap_.clear();
487 }
488
HandleTerminateTimeOut(int64_t eventId)489 void AppRunningManager::HandleTerminateTimeOut(int64_t eventId)
490 {
491 TAG_LOGD(AAFwkTag::APPMGR, "called");
492 auto abilityRecord = GetAbilityRunningRecord(eventId);
493 if (!abilityRecord) {
494 TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord is nullptr.");
495 return;
496 }
497 auto abilityToken = abilityRecord->GetToken();
498 auto appRecord = GetTerminatingAppRunningRecord(abilityToken);
499 if (!appRecord) {
500 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
501 return;
502 }
503 appRecord->AbilityTerminated(abilityToken);
504 }
505
GetTerminatingAppRunningRecord(const sptr<IRemoteObject> & abilityToken)506 std::shared_ptr<AppRunningRecord> AppRunningManager::GetTerminatingAppRunningRecord(
507 const sptr<IRemoteObject> &abilityToken)
508 {
509 std::lock_guard guard(runningRecordMapMutex_);
510 for (const auto &item : appRunningRecordMap_) {
511 const auto &appRecord = item.second;
512 if (appRecord && appRecord->GetAbilityByTerminateLists(abilityToken)) {
513 return appRecord;
514 }
515 }
516 return nullptr;
517 }
518
GetAbilityRunningRecord(const int64_t eventId)519 std::shared_ptr<AbilityRunningRecord> AppRunningManager::GetAbilityRunningRecord(const int64_t eventId)
520 {
521 TAG_LOGD(AAFwkTag::APPMGR, "called");
522 std::lock_guard guard(runningRecordMapMutex_);
523 for (auto &item : appRunningRecordMap_) {
524 if (item.second) {
525 auto abilityRecord = item.second->GetAbilityRunningRecord(eventId);
526 if (abilityRecord) {
527 return abilityRecord;
528 }
529 }
530 }
531 return nullptr;
532 }
533
GetAppRunningRecord(const int64_t eventId)534 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecord(const int64_t eventId)
535 {
536 TAG_LOGD(AAFwkTag::APPMGR, "called");
537 std::lock_guard guard(runningRecordMapMutex_);
538 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&eventId](const auto &pair) {
539 return pair.second->GetEventId() == eventId;
540 });
541 return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second);
542 }
543
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token,std::shared_ptr<AppMgrServiceInner> serviceInner)544 void AppRunningManager::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token,
545 std::shared_ptr<AppMgrServiceInner> serviceInner)
546 {
547 TAG_LOGI(AAFwkTag::APPMGR, "called");
548 if (token == nullptr) {
549 TAG_LOGE(AAFwkTag::APPMGR, "token is nullptr.");
550 return;
551 }
552
553 auto appRecord = GetAppRunningRecordByAbilityToken(token);
554 if (!appRecord) {
555 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
556 return;
557 }
558
559 std::shared_ptr<AbilityRunningRecord> abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
560 bool isSCB = false;
561 if (abilityRecord) {
562 abilityRecord->SetTerminating();
563 isSCB = abilityRecord->IsSceneBoard();
564 if (isSCB && appRecord->GetPriorityObject() && serviceInner != nullptr) {
565 pid_t pid = appRecord->GetPriorityObject()->GetPid();
566 (void)serviceInner->KillProcessByPid(pid, "AttachTimeoutKillSCB");
567 }
568 }
569
570 if ((isSCB || appRecord->IsLastAbilityRecord(token)) && (!appRecord->IsKeepAliveApp() ||
571 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) {
572 appRecord->SetTerminating(shared_from_this());
573 }
574
575 auto timeoutTask = [appRecord, token]() {
576 if (appRecord) {
577 appRecord->TerminateAbility(token, true);
578 }
579 };
580 appRecord->PostTask("DELAY_KILL_ABILITY", AMSEventHandler::KILL_PROCESS_TIMEOUT, timeoutTask);
581 }
582
PrepareTerminate(const sptr<IRemoteObject> & token,bool clearMissionFlag)583 void AppRunningManager::PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag)
584 {
585 if (token == nullptr) {
586 TAG_LOGE(AAFwkTag::APPMGR, "token is nullptr.");
587 return;
588 }
589
590 auto appRecord = GetAppRunningRecordByAbilityToken(token);
591 if (!appRecord) {
592 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
593 return;
594 }
595
596 auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
597 if (abilityRecord) {
598 abilityRecord->SetTerminating();
599 }
600
601 // set app record terminating when close last page ability
602 auto isLastAbility =
603 clearMissionFlag ? appRecord->IsLastPageAbilityRecord(token) : appRecord->IsLastAbilityRecord(token);
604 if (isLastAbility && (!appRecord->IsKeepAliveApp() ||
605 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) {
606 auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
607 if (cacheProcMgr != nullptr) {
608 cacheProcMgr->CheckAndSetProcessCacheEnable(appRecord);
609 }
610 if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
611 cacheProcMgr->PenddingCacheProcess(appRecord);
612 TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s supports process cache, not terminate record.",
613 appRecord->GetBundleName().c_str());
614 return;
615 }
616 TAG_LOGI(AAFwkTag::APPMGR, "The ability is the last in the app:%{public}s.", appRecord->GetName().c_str());
617 appRecord->SetTerminating(shared_from_this());
618 }
619 }
620
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag,std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)621 void AppRunningManager::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag,
622 std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)
623 {
624 auto appRecord = GetAppRunningRecordByAbilityToken(token);
625 if (!appRecord) {
626 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
627 return;
628 }
629
630 auto killProcess = [appRecord, token, inner = appMgrServiceInner]() {
631 if (appRecord == nullptr || token == nullptr || inner == nullptr) {
632 TAG_LOGE(AAFwkTag::APPMGR, "Pointer parameter error.");
633 return;
634 }
635 appRecord->RemoveTerminateAbilityTimeoutTask(token);
636 TAG_LOGD(AAFwkTag::APPMGR, "The ability is the last, kill application");
637 auto priorityObject = appRecord->GetPriorityObject();
638 if (priorityObject == nullptr) {
639 TAG_LOGE(AAFwkTag::APPMGR, "priorityObject is nullptr.");
640 return;
641 }
642 auto pid = priorityObject->GetPid();
643 if (pid < 0) {
644 TAG_LOGE(AAFwkTag::APPMGR, "Pid error.");
645 return;
646 }
647 auto result = inner->KillProcessByPid(pid, "TerminateAbility");
648 if (result < 0) {
649 TAG_LOGW(AAFwkTag::APPMGR, "Kill application directly failed, pid: %{public}d", pid);
650 }
651 inner->NotifyAppStatus(appRecord->GetBundleName(), CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
652 };
653
654 if (clearMissionFlag && appRecord->IsDebugApp()) {
655 killProcess();
656 return;
657 }
658
659 auto isLastAbility =
660 clearMissionFlag ? appRecord->IsLastPageAbilityRecord(token) : appRecord->IsLastAbilityRecord(token);
661 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
662 appRecord->TerminateAbility(token, true);
663 } else {
664 appRecord->TerminateAbility(token, false);
665 }
666 auto isLauncherApp = appRecord->GetApplicationInfo()->isLauncherApp;
667 auto isKeepAliveApp = appRecord->IsKeepAliveApp();
668 TAG_LOGI(AAFwkTag::APPMGR, "TerminateAbility:isLast:%{public}d,keepAlive:%{public}d",
669 isLastAbility, isKeepAliveApp);
670 if (isLastAbility && (!isKeepAliveApp ||
671 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !isLauncherApp) {
672 auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
673 if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
674 cacheProcMgr->PenddingCacheProcess(appRecord);
675 TAG_LOGI(AAFwkTag::APPMGR, "app %{public}s is not terminate app",
676 appRecord->GetBundleName().c_str());
677 if (clearMissionFlag) {
678 NotifyAppPreCache(appRecord, appMgrServiceInner);
679 }
680 return;
681 }
682 TAG_LOGI(AAFwkTag::APPMGR, "Terminate last ability in app:%{public}s.", appRecord->GetName().c_str());
683 appRecord->SetTerminating(shared_from_this());
684 if (clearMissionFlag && appMgrServiceInner != nullptr) {
685 auto delayTime = appRecord->ExtensionAbilityRecordExists() ?
686 AMSEventHandler::DELAY_KILL_EXTENSION_PROCESS_TIMEOUT : AMSEventHandler::DELAY_KILL_PROCESS_TIMEOUT;
687 appRecord->PostTask("DELAY_KILL_PROCESS", delayTime, killProcess);
688 }
689 }
690 }
691
NotifyAppPreCache(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AppMgrServiceInner> & appMgrServiceInner)692 void AppRunningManager::NotifyAppPreCache(const std::shared_ptr<AppRunningRecord>& appRecord,
693 const std::shared_ptr<AppMgrServiceInner>& appMgrServiceInner)
694 {
695 if (appMgrServiceInner == nullptr || appRecord == nullptr ||
696 appRecord->GetPriorityObject() == nullptr) {
697 return;
698 }
699 int32_t pid = appRecord->GetPriorityObject()->GetPid();
700 int32_t userId = appRecord->GetUid() / BASE_USER_RANGE;
701 auto notifyAppPreCache = [pid, userId, inner = appMgrServiceInner]() {
702 if (inner == nullptr) {
703 return;
704 }
705 inner->NotifyAppPreCache(pid, userId);
706 };
707 appRecord->PostTask("NotifyAppPreCache", 0, notifyAppPreCache);
708 }
709
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)710 void AppRunningManager::GetRunningProcessInfoByToken(
711 const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
712 {
713 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
714 auto appRecord = GetAppRunningRecordByAbilityToken(token);
715 AssignRunningProcessInfoByAppRecord(appRecord, info);
716 }
717
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info)718 int32_t AppRunningManager::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info)
719 {
720 if (pid <= 0) {
721 TAG_LOGE(AAFwkTag::APPMGR, "invalid process pid:%{public}d", pid);
722 return ERR_INVALID_OPERATION;
723 }
724 auto appRecord = GetAppRunningRecordByPid(pid);
725 return AssignRunningProcessInfoByAppRecord(appRecord, info);
726 }
727
AssignRunningProcessInfoByAppRecord(std::shared_ptr<AppRunningRecord> appRecord,AppExecFwk::RunningProcessInfo & info) const728 int32_t AppRunningManager::AssignRunningProcessInfoByAppRecord(
729 std::shared_ptr<AppRunningRecord> appRecord, AppExecFwk::RunningProcessInfo &info) const
730 {
731 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
732 if (!appRecord) {
733 TAG_LOGE(AAFwkTag::APPMGR, "null");
734 return ERR_INVALID_OPERATION;
735 }
736
737 info.processName_ = appRecord->GetProcessName();
738 info.pid_ = appRecord->GetPriorityObject()->GetPid();
739 info.uid_ = appRecord->GetUid();
740 info.bundleNames.emplace_back(appRecord->GetBundleName());
741 info.state_ = static_cast<AppExecFwk::AppProcessState>(appRecord->GetState());
742 info.isContinuousTask = appRecord->IsContinuousTask();
743 info.isKeepAlive = appRecord->IsKeepAliveApp();
744 info.isFocused = appRecord->GetFocusFlag();
745 info.isTestProcess = (appRecord->GetUserTestInfo() != nullptr);
746 info.startTimeMillis_ = appRecord->GetAppStartTime();
747 info.isAbilityForegrounding = appRecord->GetAbilityForegroundingFlag();
748 info.isTestMode = info.isTestProcess && system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
749 info.extensionType_ = appRecord->GetExtensionType();
750 info.processType_ = appRecord->GetProcessType();
751 info.isStrictMode = appRecord->IsStrictMode();
752 auto appInfo = appRecord->GetApplicationInfo();
753 if (appInfo) {
754 info.bundleType = static_cast<int32_t>(appInfo->bundleType);
755 }
756 if (appInfo && (static_cast<int32_t>(appInfo->multiAppMode.multiAppModeType) ==
757 static_cast<int32_t>(MultiAppModeType::APP_CLONE))) {
758 info.appCloneIndex = appRecord->GetAppIndex();
759 }
760 return ERR_OK;
761 }
762
SetAbilityForegroundingFlagToAppRecord(const pid_t pid)763 void AppRunningManager::SetAbilityForegroundingFlagToAppRecord(const pid_t pid)
764 {
765 auto appRecord = GetAppRunningRecordByPid(pid);
766 if (appRecord == nullptr) {
767 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
768 return;
769 }
770 appRecord->SetAbilityForegroundingFlag();
771 }
772
ClipStringContent(const std::regex & re,const std::string & source,std::string & afterCutStr)773 void AppRunningManager::ClipStringContent(const std::regex &re, const std::string &source, std::string &afterCutStr)
774 {
775 std::smatch basket;
776 if (std::regex_search(source, basket, re)) {
777 afterCutStr = basket.prefix().str() + basket.suffix().str();
778 }
779 }
780
GetForegroundApplications(std::vector<AppStateData> & list)781 void AppRunningManager::GetForegroundApplications(std::vector<AppStateData> &list)
782 {
783 std::lock_guard guard(runningRecordMapMutex_);
784 for (const auto &item : appRunningRecordMap_) {
785 const auto &appRecord = item.second;
786 if (!appRecord) {
787 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
788 return;
789 }
790 auto state = appRecord->GetState();
791 if (state == ApplicationState::APP_STATE_FOREGROUND) {
792 AppStateData appData;
793 appData.bundleName = appRecord->GetBundleName();
794 appData.uid = appRecord->GetUid();
795 appData.pid = appRecord->GetPriorityObject()->GetPid();
796 appData.state = static_cast<int32_t>(ApplicationState::APP_STATE_FOREGROUND);
797 auto appInfo = appRecord->GetApplicationInfo();
798 appData.accessTokenId = appInfo ? appInfo->accessTokenId : 0;
799 appData.extensionType = appRecord->GetExtensionType();
800 appData.isFocused = appRecord->GetFocusFlag();
801 appData.appIndex = appRecord->GetAppIndex();
802 list.push_back(appData);
803 TAG_LOGD(AAFwkTag::APPMGR, "bundleName:%{public}s", appData.bundleName.c_str());
804 }
805 }
806 }
UpdateConfiguration(const Configuration & config,const int32_t userId)807 int32_t AppRunningManager::UpdateConfiguration(const Configuration& config, const int32_t userId)
808 {
809 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
810 std::vector<std::string> changeKeyV;
811 configuration_->CompareDifferent(changeKeyV, config);
812 if (!changeKeyV.empty()) {
813 configuration_->Merge(changeKeyV, config);
814 }
815
816 auto appRunningMap = GetAppRunningRecordMap();
817 TAG_LOGD(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningMap.size());
818 int32_t result = ERR_OK;
819 for (const auto& item : appRunningMap) {
820 const auto& appRecord = item.second;
821 if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
822 TAG_LOGD(AAFwkTag::APPMGR, "app not ready, appName is %{public}s", appRecord->GetBundleName().c_str());
823 continue;
824 }
825 if (!(userId == -1 || appRecord->GetUid() / BASE_USER_RANGE == 0 ||
826 appRecord->GetUid() / BASE_USER_RANGE == userId)) {
827 continue;
828 }
829 if (appRecord && !isCollaboratorReserveType(appRecord)) {
830 TAG_LOGD(AAFwkTag::APPMGR, "Notification app [%{public}s]", appRecord->GetName().c_str());
831 std::lock_guard guard(updateConfigurationDelayedLock_);
832 if (appRecord->NeedUpdateConfigurationBackground() ||
833 appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
834 updateConfigurationDelayedMap_[appRecord->GetRecordId()] = false;
835 result = appRecord->UpdateConfiguration(config);
836 } else {
837 updateConfigurationDelayedMap_[appRecord->GetRecordId()] = true;
838 }
839 }
840 }
841 return result;
842 }
843
UpdateConfigurationByBundleName(const Configuration & config,const std::string & name)844 int32_t AppRunningManager::UpdateConfigurationByBundleName(const Configuration &config, const std::string &name)
845 {
846 auto appRunningMap = GetAppRunningRecordMap();
847 int32_t result = ERR_OK;
848 for (const auto &item : appRunningMap) {
849 const auto &appRecord = item.second;
850 if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
851 TAG_LOGD(AAFwkTag::APPMGR, "app not ready, appName is %{public}s", appRecord->GetBundleName().c_str());
852 continue;
853 }
854 if (appRecord && !isCollaboratorReserveType(appRecord) && appRecord->GetBundleName() == name) {
855 TAG_LOGD(AAFwkTag::APPMGR, "Notification app [%{public}s]", appRecord->GetName().c_str());
856 result = appRecord->UpdateConfiguration(config);
857 }
858 }
859 return result;
860 }
861
isCollaboratorReserveType(const std::shared_ptr<AppRunningRecord> & appRecord)862 bool AppRunningManager::isCollaboratorReserveType(const std::shared_ptr<AppRunningRecord> &appRecord)
863 {
864 std::string bundleName = appRecord->GetApplicationInfo()->name;
865 bool isReserveType = bundleName == SHELL_ASSISTANT_BUNDLENAME;
866 if (isReserveType) {
867 TAG_LOGI(AAFwkTag::APPMGR, "isReserveType app [%{public}s]", appRecord->GetName().c_str());
868 }
869 return isReserveType;
870 }
871
NotifyMemoryLevel(int32_t level)872 int32_t AppRunningManager::NotifyMemoryLevel(int32_t level)
873 {
874 std::unordered_set<int32_t> frozenPids;
875 AAFwk::ResSchedUtil::GetInstance().GetAllFrozenPidsFromRSS(frozenPids);
876 auto appRunningMap = GetAppRunningRecordMap();
877 for (const auto &item : appRunningMap) {
878 const auto &appRecord = item.second;
879 if (!appRecord) {
880 TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
881 continue;
882 }
883 auto priorityObject = appRecord->GetPriorityObject();
884 if (!priorityObject) {
885 TAG_LOGW(AAFwkTag::APPMGR, "priorityObject null");
886 continue;
887 }
888 auto pid = priorityObject->GetPid();
889 if (frozenPids.count(pid) == 0) {
890 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] memory level = %{public}d", pid, level);
891 appRecord->ScheduleMemoryLevel(level);
892 } else {
893 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] is frozen", pid);
894 }
895 }
896 return ERR_OK;
897 }
898
NotifyProcMemoryLevel(const std::map<pid_t,MemoryLevel> & procLevelMap)899 int32_t AppRunningManager::NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap)
900 {
901 std::unordered_set<int32_t> frozenPids;
902 AAFwk::ResSchedUtil::GetInstance().GetAllFrozenPidsFromRSS(frozenPids);
903 auto appRunningMap = GetAppRunningRecordMap();
904 for (const auto &item : appRunningMap) {
905 const auto &appRecord = item.second;
906 if (!appRecord) {
907 TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
908 continue;
909 }
910 auto priorityObject = appRecord->GetPriorityObject();
911 if (!priorityObject) {
912 TAG_LOGW(AAFwkTag::APPMGR, "priorityObject null");
913 continue;
914 }
915 auto pid = priorityObject->GetPid();
916 if (frozenPids.count(pid) == 0) {
917 auto it = procLevelMap.find(pid);
918 if (it == procLevelMap.end()) {
919 TAG_LOGW(AAFwkTag::APPMGR, "proc[pid=%{public}d] is not found in procLevelMap.", pid);
920 } else {
921 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] memory level = %{public}d", pid, it->second);
922 appRecord->ScheduleMemoryLevel(it->second);
923 }
924 } else {
925 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] is frozen", pid);
926 }
927 }
928 return ERR_OK;
929 }
930
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)931 int32_t AppRunningManager::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
932 {
933 std::shared_ptr<AppRunningRecord> appRecord;
934 {
935 std::lock_guard guard(runningRecordMapMutex_);
936 TAG_LOGI(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningRecordMap_.size());
937 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
938 auto priorityObject = pair.second->GetPriorityObject();
939 return priorityObject && priorityObject->GetPid() == pid;
940 });
941 if (iter == appRunningRecordMap_.end()) {
942 TAG_LOGE(AAFwkTag::APPMGR, "No matching application was found.");
943 return ERR_INVALID_VALUE;
944 }
945 appRecord = iter->second;
946 if (appRecord == nullptr) {
947 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
948 return ERR_INVALID_VALUE;
949 }
950 }
951 appRecord->ScheduleHeapMemory(pid, mallocInfo);
952 return ERR_OK;
953 }
954
DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)955 int32_t AppRunningManager::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
956 {
957 int32_t pid = static_cast<int32_t>(info.pid);
958 auto appRecord = GetAppRunningRecordByPid(pid);
959 if (appRecord == nullptr) {
960 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
961 return ERR_INVALID_VALUE;
962 }
963 appRecord->ScheduleJsHeapMemory(info);
964 return ERR_OK;
965 }
966
GetAppRunningRecordByRenderPid(const pid_t pid)967 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByRenderPid(const pid_t pid)
968 {
969 std::lock_guard guard(runningRecordMapMutex_);
970 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
971 auto renderRecordMap = pair.second->GetRenderRecordMap();
972 if (renderRecordMap.empty()) {
973 return false;
974 }
975 for (auto it : renderRecordMap) {
976 auto renderRecord = it.second;
977 if (renderRecord && renderRecord->GetPid() == pid) {
978 return true;
979 }
980 }
981 return false;
982 });
983 return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second);
984 }
985
OnRemoteRenderDied(const wptr<IRemoteObject> & remote)986 std::shared_ptr<RenderRecord> AppRunningManager::OnRemoteRenderDied(const wptr<IRemoteObject> &remote)
987 {
988 if (remote == nullptr) {
989 TAG_LOGE(AAFwkTag::APPMGR, "remote is null");
990 return nullptr;
991 }
992 sptr<IRemoteObject> object = remote.promote();
993 if (!object) {
994 TAG_LOGE(AAFwkTag::APPMGR, "promote failed.");
995 return nullptr;
996 }
997
998 std::lock_guard guard(runningRecordMapMutex_);
999 std::shared_ptr<RenderRecord> renderRecord;
1000 const auto &it =
1001 std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(),
1002 [&object, &renderRecord](const auto &pair) {
1003 if (!pair.second) {
1004 return false;
1005 }
1006
1007 auto renderRecordMap = pair.second->GetRenderRecordMap();
1008 if (renderRecordMap.empty()) {
1009 return false;
1010 }
1011 for (auto iter : renderRecordMap) {
1012 if (iter.second == nullptr) {
1013 continue;
1014 }
1015 auto scheduler = iter.second->GetScheduler();
1016 if (scheduler && scheduler->AsObject() == object) {
1017 renderRecord = iter.second;
1018 return true;
1019 }
1020 }
1021 return false;
1022 });
1023 if (it != appRunningRecordMap_.end()) {
1024 auto appRecord = it->second;
1025 appRecord->RemoveRenderRecord(renderRecord);
1026 TAG_LOGI(AAFwkTag::APPMGR, "RemoveRenderRecord pid:%{public}d, uid:%{public}d.", renderRecord->GetPid(),
1027 renderRecord->GetUid());
1028 return renderRecord;
1029 }
1030 return nullptr;
1031 }
1032
GetAppRunningStateByBundleName(const std::string & bundleName)1033 bool AppRunningManager::GetAppRunningStateByBundleName(const std::string &bundleName)
1034 {
1035 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1036 TAG_LOGD(AAFwkTag::APPMGR, "called");
1037 std::lock_guard guard(runningRecordMapMutex_);
1038 for (const auto &item : appRunningRecordMap_) {
1039 const auto &appRecord = item.second;
1040 if (appRecord && appRecord->GetBundleName() == bundleName) {
1041 TAG_LOGD(AAFwkTag::APPMGR, "Process of [%{public}s] is running, processName: %{public}s.",
1042 bundleName.c_str(), appRecord->GetProcessName().c_str());
1043 if (IPCSkeleton::GetCallingUid() == QUICKFIX_UID && appRecord->GetPriorityObject() != nullptr) {
1044 TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d.", appRecord->GetPriorityObject()->GetPid());
1045 }
1046 return true;
1047 }
1048 }
1049 return false;
1050 }
1051
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1052 int32_t AppRunningManager::NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1053 {
1054 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1055 TAG_LOGD(AAFwkTag::APPMGR, "called");
1056 int32_t result = ERR_OK;
1057 bool loadSucceed = false;
1058 auto callbackByRecord = sptr<QuickFixCallbackWithRecord>::MakeSptr(callback);
1059 if (callbackByRecord == nullptr) {
1060 TAG_LOGE(AAFwkTag::APPMGR, "Failed to create callback record.");
1061 return ERR_INVALID_VALUE;
1062 }
1063
1064 auto appRunningMap = GetAppRunningRecordMap();
1065 for (const auto &item : appRunningMap) {
1066 const auto &appRecord = item.second;
1067 if (appRecord && appRecord->GetBundleName() == bundleName) {
1068 auto recordId = appRecord->GetRecordId();
1069 TAG_LOGD(AAFwkTag::APPMGR, "Notify application [%{public}s] load patch, record id %{public}d.",
1070 appRecord->GetProcessName().c_str(), recordId);
1071 callbackByRecord->AddRecordId(recordId);
1072 result = appRecord->NotifyLoadRepairPatch(bundleName, callbackByRecord, recordId);
1073 if (result == ERR_OK) {
1074 loadSucceed = true;
1075 } else {
1076 callbackByRecord->RemoveRecordId(recordId);
1077 }
1078 }
1079 }
1080 return loadSucceed == true ? ERR_OK : result;
1081 }
1082
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1083 int32_t AppRunningManager::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1084 {
1085 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1086 TAG_LOGD(AAFwkTag::APPMGR, "called");
1087 int32_t result = ERR_OK;
1088 bool reloadPageSucceed = false;
1089 auto callbackByRecord = sptr<QuickFixCallbackWithRecord>::MakeSptr(callback);
1090 if (callbackByRecord == nullptr) {
1091 TAG_LOGE(AAFwkTag::APPMGR, "Failed to create callback record.");
1092 return ERR_INVALID_VALUE;
1093 }
1094
1095 auto appRunningMap = GetAppRunningRecordMap();
1096 for (const auto &item : appRunningMap) {
1097 const auto &appRecord = item.second;
1098 if (appRecord && appRecord->GetBundleName() == bundleName) {
1099 auto recordId = appRecord->GetRecordId();
1100 TAG_LOGD(AAFwkTag::APPMGR, "Notify application [%{public}s] reload page, record id %{public}d.",
1101 appRecord->GetProcessName().c_str(), recordId);
1102 callbackByRecord->AddRecordId(recordId);
1103 result = appRecord->NotifyHotReloadPage(callbackByRecord, recordId);
1104 if (result == ERR_OK) {
1105 reloadPageSucceed = true;
1106 } else {
1107 callbackByRecord->RemoveRecordId(recordId);
1108 }
1109 }
1110 }
1111 return reloadPageSucceed == true ? ERR_OK : result;
1112 }
1113
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1114 int32_t AppRunningManager::NotifyUnLoadRepairPatch(const std::string &bundleName,
1115 const sptr<IQuickFixCallback> &callback)
1116 {
1117 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1118 TAG_LOGD(AAFwkTag::APPMGR, "called");
1119 int32_t result = ERR_OK;
1120 bool unLoadSucceed = false;
1121 auto callbackByRecord = sptr<QuickFixCallbackWithRecord>::MakeSptr(callback);
1122 if (callbackByRecord == nullptr) {
1123 TAG_LOGE(AAFwkTag::APPMGR, "Failed to create callback record.");
1124 return ERR_INVALID_VALUE;
1125 }
1126
1127 auto appRunningMap = GetAppRunningRecordMap();
1128 for (const auto &item : appRunningMap) {
1129 const auto &appRecord = item.second;
1130 if (appRecord && appRecord->GetBundleName() == bundleName) {
1131 auto recordId = appRecord->GetRecordId();
1132 TAG_LOGD(AAFwkTag::APPMGR, "Notify application [%{public}s] unload patch, record id %{public}d.",
1133 appRecord->GetProcessName().c_str(), recordId);
1134 callbackByRecord->AddRecordId(recordId);
1135 result = appRecord->NotifyUnLoadRepairPatch(bundleName, callbackByRecord, recordId);
1136 if (result == ERR_OK) {
1137 unLoadSucceed = true;
1138 } else {
1139 callbackByRecord->RemoveRecordId(recordId);
1140 }
1141 }
1142 }
1143 return unLoadSucceed == true ? ERR_OK : result;
1144 }
1145
IsApplicationFirstForeground(const AppRunningRecord & foregroundingRecord)1146 bool AppRunningManager::IsApplicationFirstForeground(const AppRunningRecord &foregroundingRecord)
1147 {
1148 TAG_LOGD(AAFwkTag::APPMGR, "called");
1149 if (AAFwk::UIExtensionUtils::IsUIExtension(foregroundingRecord.GetExtensionType())
1150 || AAFwk::UIExtensionUtils::IsWindowExtension(foregroundingRecord.GetExtensionType())) {
1151 return false;
1152 }
1153
1154 std::lock_guard guard(runningRecordMapMutex_);
1155 for (const auto &item : appRunningRecordMap_) {
1156 const auto &appRecord = item.second;
1157 if (appRecord == nullptr || appRecord->GetBundleName() != foregroundingRecord.GetBundleName()
1158 || AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
1159 || AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
1160 || appRecord->GetAppIndex() != foregroundingRecord.GetAppIndex()) {
1161 continue;
1162 }
1163 auto state = appRecord->GetState();
1164 if (state == ApplicationState::APP_STATE_FOREGROUND &&
1165 appRecord->GetRecordId() != foregroundingRecord.GetRecordId()) {
1166 return false;
1167 }
1168 }
1169 return true;
1170 }
1171
IsApplicationBackground(const AppRunningRecord & backgroundingRecord)1172 bool AppRunningManager::IsApplicationBackground(const AppRunningRecord &backgroundingRecord)
1173 {
1174 TAG_LOGD(AAFwkTag::APPMGR, "called");
1175 std::lock_guard guard(runningRecordMapMutex_);
1176 for (const auto &item : appRunningRecordMap_) {
1177 const auto &appRecord = item.second;
1178 if (appRecord == nullptr) {
1179 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1180 return false;
1181 }
1182 if (AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
1183 || AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
1184 || appRecord->GetAppIndex() != backgroundingRecord.GetAppIndex()) {
1185 continue;
1186 }
1187 auto state = appRecord->GetState();
1188 if (appRecord && appRecord->GetBundleName() == backgroundingRecord.GetBundleName() &&
1189 state == ApplicationState::APP_STATE_FOREGROUND) {
1190 return false;
1191 }
1192 }
1193 return true;
1194 }
1195
OnWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)1196 void AppRunningManager::OnWindowVisibilityChanged(
1197 const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
1198 {
1199 TAG_LOGD(AAFwkTag::APPMGR, "called");
1200 std::set<int32_t> pids;
1201 for (const auto &info : windowVisibilityInfos) {
1202 if (info == nullptr) {
1203 TAG_LOGE(AAFwkTag::APPMGR, "Window visibility info is nullptr.");
1204 continue;
1205 }
1206 if (pids.find(info->pid_) != pids.end()) {
1207 continue;
1208 }
1209 auto appRecord = GetAppRunningRecordByPid(info->pid_);
1210 if (appRecord == nullptr) {
1211 TAG_LOGE(AAFwkTag::APPMGR, "App running record is nullptr.");
1212 return;
1213 }
1214 TAG_LOGD(AAFwkTag::APPMGR, "The visibility of %{public}s was changed.", appRecord->GetBundleName().c_str());
1215 appRecord->OnWindowVisibilityChanged(windowVisibilityInfos);
1216 pids.emplace(info->pid_);
1217 }
1218 }
1219
IsApplicationFirstFocused(const AppRunningRecord & focusedRecord)1220 bool AppRunningManager::IsApplicationFirstFocused(const AppRunningRecord &focusedRecord)
1221 {
1222 TAG_LOGD(AAFwkTag::APPMGR, "called");
1223 std::lock_guard guard(runningRecordMapMutex_);
1224 for (const auto &item : appRunningRecordMap_) {
1225 const auto &appRecord = item.second;
1226 if (appRecord == nullptr || appRecord->GetBundleName() != focusedRecord.GetBundleName()) {
1227 continue;
1228 }
1229 if (appRecord->GetFocusFlag() && appRecord->GetRecordId() != focusedRecord.GetRecordId()) {
1230 return false;
1231 }
1232 }
1233 return true;
1234 }
1235
IsApplicationUnfocused(const std::string & bundleName)1236 bool AppRunningManager::IsApplicationUnfocused(const std::string &bundleName)
1237 {
1238 TAG_LOGD(AAFwkTag::APPMGR, "check is application unfocused.");
1239 std::lock_guard guard(runningRecordMapMutex_);
1240 for (const auto &item : appRunningRecordMap_) {
1241 const auto &appRecord = item.second;
1242 if (appRecord && appRecord->GetBundleName() == bundleName && appRecord->GetFocusFlag()) {
1243 return false;
1244 }
1245 }
1246 return true;
1247 }
1248
SetAttachAppDebug(const std::string & bundleName,const bool & isAttachDebug)1249 void AppRunningManager::SetAttachAppDebug(const std::string &bundleName, const bool &isAttachDebug)
1250 {
1251 TAG_LOGD(AAFwkTag::APPMGR, "called");
1252 auto appRunningMap = GetAppRunningRecordMap();
1253 for (const auto &item : appRunningMap) {
1254 const auto &appRecord = item.second;
1255 if (appRecord == nullptr) {
1256 continue;
1257 }
1258 if (appRecord->GetBundleName() == bundleName) {
1259 TAG_LOGD(AAFwkTag::APPMGR, "The application: %{public}s will be set debug mode.", bundleName.c_str());
1260 appRecord->SetAttachDebug(isAttachDebug);
1261 }
1262 }
1263 }
1264
GetAppDebugInfosByBundleName(const std::string & bundleName,const bool & isDetachDebug)1265 std::vector<AppDebugInfo> AppRunningManager::GetAppDebugInfosByBundleName(
1266 const std::string &bundleName, const bool &isDetachDebug)
1267 {
1268 TAG_LOGD(AAFwkTag::APPMGR, "called");
1269 std::lock_guard guard(runningRecordMapMutex_);
1270 std::vector<AppDebugInfo> debugInfos;
1271 for (const auto &item : appRunningRecordMap_) {
1272 const auto &appRecord = item.second;
1273 if (appRecord == nullptr || appRecord->GetBundleName() != bundleName ||
1274 (isDetachDebug && (appRecord->IsDebugApp() || appRecord->IsAssertionPause()))) {
1275 continue;
1276 }
1277
1278 AppDebugInfo debugInfo;
1279 debugInfo.bundleName = bundleName;
1280 auto priorityObject = appRecord->GetPriorityObject();
1281 if (priorityObject) {
1282 debugInfo.pid = priorityObject->GetPid();
1283 }
1284 debugInfo.uid = appRecord->GetUid();
1285 debugInfo.isDebugStart = (appRecord->IsDebugApp() || appRecord->IsAssertionPause());
1286 debugInfos.emplace_back(debugInfo);
1287 }
1288 return debugInfos;
1289 }
1290
GetAbilityTokensByBundleName(const std::string & bundleName,std::vector<sptr<IRemoteObject>> & abilityTokens)1291 void AppRunningManager::GetAbilityTokensByBundleName(
1292 const std::string &bundleName, std::vector<sptr<IRemoteObject>> &abilityTokens)
1293 {
1294 TAG_LOGD(AAFwkTag::APPMGR, "called");
1295 std::lock_guard guard(runningRecordMapMutex_);
1296 for (const auto &item : appRunningRecordMap_) {
1297 const auto &appRecord = item.second;
1298 if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) {
1299 continue;
1300 }
1301
1302 for (const auto &token : appRecord->GetAbilities()) {
1303 abilityTokens.emplace_back(token.first);
1304 }
1305 }
1306 }
1307
GetAppRunningRecordByChildProcessPid(const pid_t pid)1308 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByChildProcessPid(const pid_t pid)
1309 {
1310 std::lock_guard guard(runningRecordMapMutex_);
1311 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
1312 auto childProcessRecordMap = pair.second->GetChildProcessRecordMap();
1313 return childProcessRecordMap.find(pid) != childProcessRecordMap.end();
1314 });
1315 if (iter != appRunningRecordMap_.end()) {
1316 return iter->second;
1317 }
1318 return nullptr;
1319 }
1320
IsChildProcessReachLimit(uint32_t accessTokenId)1321 bool AppRunningManager::IsChildProcessReachLimit(uint32_t accessTokenId)
1322 {
1323 TAG_LOGD(AAFwkTag::APPMGR, "called.");
1324 int32_t childCount = 0;
1325 std::lock_guard guard(runningRecordMapMutex_);
1326 for (auto &pair : appRunningRecordMap_) {
1327 auto appRecord = pair.second;
1328 if (!appRecord || !appRecord->GetApplicationInfo() ||
1329 accessTokenId != appRecord->GetApplicationInfo()->accessTokenId) {
1330 continue;
1331 }
1332 childCount += appRecord->GetChildProcessCount();
1333 }
1334 return childCount >= AAFwk::AppUtils::GetInstance().MaxChildProcess();
1335 }
1336
OnChildProcessRemoteDied(const wptr<IRemoteObject> & remote)1337 std::shared_ptr<ChildProcessRecord> AppRunningManager::OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote)
1338 {
1339 TAG_LOGE(AAFwkTag::APPMGR, "On child process remote died.");
1340 if (remote == nullptr) {
1341 TAG_LOGE(AAFwkTag::APPMGR, "remote is null");
1342 return nullptr;
1343 }
1344 sptr<IRemoteObject> object = remote.promote();
1345 if (!object) {
1346 TAG_LOGE(AAFwkTag::APPMGR, "promote failed.");
1347 return nullptr;
1348 }
1349
1350 std::lock_guard guard(runningRecordMapMutex_);
1351 std::shared_ptr<ChildProcessRecord> childRecord;
1352 const auto &it = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(),
1353 [&object, &childRecord](const auto &pair) {
1354 auto appRecord = pair.second;
1355 if (!appRecord) {
1356 return false;
1357 }
1358 auto childRecordMap = appRecord->GetChildProcessRecordMap();
1359 if (childRecordMap.empty()) {
1360 return false;
1361 }
1362 for (auto iter : childRecordMap) {
1363 if (iter.second == nullptr) {
1364 continue;
1365 }
1366 auto scheduler = iter.second->GetScheduler();
1367 if (scheduler && scheduler->AsObject() == object) {
1368 childRecord = iter.second;
1369 return true;
1370 }
1371 }
1372 return false;
1373 });
1374 if (it != appRunningRecordMap_.end()) {
1375 auto appRecord = it->second;
1376 appRecord->RemoveChildProcessRecord(childRecord);
1377 TAG_LOGI(AAFwkTag::APPMGR, "RemoveChildProcessRecord pid:%{public}d, uid:%{public}d.", childRecord->GetPid(),
1378 childRecord->GetUid());
1379 return childRecord;
1380 }
1381 return nullptr;
1382 }
1383
SignRestartAppFlag(int32_t uid)1384 int32_t AppRunningManager::SignRestartAppFlag(int32_t uid)
1385 {
1386 TAG_LOGD(AAFwkTag::APPMGR, "called");
1387 std::lock_guard guard(runningRecordMapMutex_);
1388 for (const auto &item : appRunningRecordMap_) {
1389 const auto &appRecord = item.second;
1390 if (appRecord == nullptr || appRecord->GetUid() != uid) {
1391 continue;
1392 }
1393 TAG_LOGD(AAFwkTag::APPMGR, "sign");
1394 appRecord->SetRestartAppFlag(true);
1395 return ERR_OK;
1396 }
1397 TAG_LOGE(AAFwkTag::APPMGR, "Not find apprecord.");
1398 return ERR_INVALID_VALUE;
1399 }
1400
GetAppRunningUniqueIdByPid(pid_t pid,std::string & appRunningUniqueId)1401 int32_t AppRunningManager::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId)
1402 {
1403 TAG_LOGD(AAFwkTag::APPMGR, "called");
1404 auto appRecord = GetAppRunningRecordByPid(pid);
1405 if (appRecord == nullptr) {
1406 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1407 return ERR_INVALID_VALUE;
1408 }
1409 appRunningUniqueId = std::to_string(appRecord->GetAppStartTime());
1410 TAG_LOGD(AAFwkTag::APPMGR, "appRunningUniqueId = %{public}s.", appRunningUniqueId.c_str());
1411 return ERR_OK;
1412 }
1413
GetAllUIExtensionRootHostPid(pid_t pid,std::vector<pid_t> & hostPids)1414 int32_t AppRunningManager::GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids)
1415 {
1416 TAG_LOGD(AAFwkTag::APPMGR, "called");
1417 std::lock_guard guard(uiExtensionMapLock_);
1418 for (auto &item: uiExtensionLauncherMap_) {
1419 auto temp = item.second.second;
1420 if (temp == pid) {
1421 hostPids.emplace_back(item.second.first);
1422 }
1423 }
1424 std::string hostPidStr = std::accumulate(hostPids.begin(), hostPids.end(), std::string(),
1425 [](const std::string& a, pid_t b) {
1426 return a + std::to_string(b) + " ";
1427 });
1428 TAG_LOGD(AAFwkTag::APPMGR, "pid: %{public}s, hostPid: %{public}s.", std::to_string(pid).c_str(),
1429 hostPidStr.c_str());
1430 return ERR_OK;
1431 }
1432
GetAllUIExtensionProviderPid(pid_t hostPid,std::vector<pid_t> & providerPids)1433 int32_t AppRunningManager::GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids)
1434 {
1435 std::lock_guard guard(uiExtensionMapLock_);
1436 for (auto &item: uiExtensionLauncherMap_) {
1437 auto temp = item.second.first;
1438 if (temp == hostPid) {
1439 providerPids.emplace_back(item.second.second);
1440 }
1441 }
1442
1443 return ERR_OK;
1444 }
1445
AddUIExtensionLauncherItem(int32_t uiExtensionAbilityId,pid_t hostPid,pid_t providerPid)1446 int32_t AppRunningManager::AddUIExtensionLauncherItem(int32_t uiExtensionAbilityId, pid_t hostPid, pid_t providerPid)
1447 {
1448 std::lock_guard guard(uiExtensionMapLock_);
1449 uiExtensionLauncherMap_.emplace(uiExtensionAbilityId, std::pair<pid_t, pid_t>(hostPid, providerPid));
1450 return ERR_OK;
1451 }
1452
RemoveUIExtensionLauncherItem(pid_t pid)1453 int32_t AppRunningManager::RemoveUIExtensionLauncherItem(pid_t pid)
1454 {
1455 std::lock_guard guard(uiExtensionMapLock_);
1456 for (auto it = uiExtensionLauncherMap_.begin(); it != uiExtensionLauncherMap_.end();) {
1457 if (it->second.first == pid || it->second.second == pid) {
1458 it = uiExtensionLauncherMap_.erase(it);
1459 continue;
1460 }
1461 it++;
1462 }
1463
1464 return ERR_OK;
1465 }
1466
RemoveUIExtensionLauncherItemById(int32_t uiExtensionAbilityId)1467 int32_t AppRunningManager::RemoveUIExtensionLauncherItemById(int32_t uiExtensionAbilityId)
1468 {
1469 std::lock_guard guard(uiExtensionMapLock_);
1470 for (auto it = uiExtensionLauncherMap_.begin(); it != uiExtensionLauncherMap_.end();) {
1471 if (it->first == uiExtensionAbilityId) {
1472 it = uiExtensionLauncherMap_.erase(it);
1473 continue;
1474 }
1475 it++;
1476 }
1477
1478 return ERR_OK;
1479 }
1480
DumpIpcAllStart(std::string & result)1481 int AppRunningManager::DumpIpcAllStart(std::string& result)
1482 {
1483 TAG_LOGD(AAFwkTag::APPMGR, "called");
1484 int errCode = DumpErrorCode::ERR_OK;
1485 for (const auto &item : GetAppRunningRecordMap()) {
1486 const auto &appRecord = item.second;
1487 TAG_LOGD(AAFwkTag::APPMGR, "AppRunningManager::DumpIpcAllStart::pid:%{public}d",
1488 appRecord->GetPriorityObject()->GetPid());
1489 std::string currentResult;
1490 errCode = appRecord->DumpIpcStart(currentResult);
1491 result += currentResult + "\n";
1492 if (errCode != DumpErrorCode::ERR_OK) {
1493 return errCode;
1494 }
1495 }
1496 return errCode;
1497 }
1498
DumpIpcAllStop(std::string & result)1499 int AppRunningManager::DumpIpcAllStop(std::string& result)
1500 {
1501 TAG_LOGD(AAFwkTag::APPMGR, "called");
1502 int errCode = DumpErrorCode::ERR_OK;
1503 for (const auto &item : GetAppRunningRecordMap()) {
1504 const auto &appRecord = item.second;
1505 TAG_LOGD(AAFwkTag::APPMGR, "AppRunningManager::DumpIpcAllStop::pid:%{public}d",
1506 appRecord->GetPriorityObject()->GetPid());
1507 std::string currentResult;
1508 errCode = appRecord->DumpIpcStop(currentResult);
1509 result += currentResult + "\n";
1510 if (errCode != DumpErrorCode::ERR_OK) {
1511 return errCode;
1512 }
1513 }
1514 return errCode;
1515 }
1516
DumpIpcAllStat(std::string & result)1517 int AppRunningManager::DumpIpcAllStat(std::string& result)
1518 {
1519 TAG_LOGD(AAFwkTag::APPMGR, "called");
1520 int errCode = DumpErrorCode::ERR_OK;
1521 for (const auto &item : GetAppRunningRecordMap()) {
1522 const auto &appRecord = item.second;
1523 TAG_LOGD(AAFwkTag::APPMGR, "AppRunningManager::DumpIpcAllStat::pid:%{public}d",
1524 appRecord->GetPriorityObject()->GetPid());
1525 std::string currentResult;
1526 errCode = appRecord->DumpIpcStat(currentResult);
1527 result += currentResult + "\n";
1528 if (errCode != DumpErrorCode::ERR_OK) {
1529 return errCode;
1530 }
1531 }
1532 return errCode;
1533 }
1534
DumpIpcStart(const int32_t pid,std::string & result)1535 int AppRunningManager::DumpIpcStart(const int32_t pid, std::string& result)
1536 {
1537 TAG_LOGD(AAFwkTag::APPMGR, "called");
1538 const auto& appRecord = GetAppRunningRecordByPid(pid);
1539 if (!appRecord) {
1540 result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
1541 .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
1542 .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
1543 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1544 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1545 }
1546 return appRecord->DumpIpcStart(result);
1547 }
1548
DumpIpcStop(const int32_t pid,std::string & result)1549 int AppRunningManager::DumpIpcStop(const int32_t pid, std::string& result)
1550 {
1551 TAG_LOGD(AAFwkTag::APPMGR, "called");
1552 const auto& appRecord = GetAppRunningRecordByPid(pid);
1553 if (!appRecord) {
1554 result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
1555 .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
1556 .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
1557 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1558 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1559 }
1560 return appRecord->DumpIpcStop(result);
1561 }
1562
DumpIpcStat(const int32_t pid,std::string & result)1563 int AppRunningManager::DumpIpcStat(const int32_t pid, std::string& result)
1564 {
1565 TAG_LOGD(AAFwkTag::APPMGR, "called");
1566 const auto& appRecord = GetAppRunningRecordByPid(pid);
1567 if (!appRecord) {
1568 result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
1569 .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
1570 .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
1571 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1572 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1573 }
1574 return appRecord->DumpIpcStat(result);
1575 }
1576
DumpFfrt(const std::vector<int32_t> & pids,std::string & result)1577 int AppRunningManager::DumpFfrt(const std::vector<int32_t>& pids, std::string& result)
1578 {
1579 TAG_LOGD(AAFwkTag::APPMGR, "called");
1580 int errCode = DumpErrorCode::ERR_OK;
1581 size_t count = 0;
1582 for (const auto& pid : pids) {
1583 TAG_LOGD(AAFwkTag::APPMGR, "DumpFfrt current pid:%{public}d", pid);
1584 const auto& appRecord = GetAppRunningRecordByPid(pid);
1585 if (!appRecord) {
1586 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1587 ++count;
1588 continue;
1589 }
1590 std::string currentResult;
1591 errCode = appRecord->DumpFfrt(currentResult);
1592 if (errCode != DumpErrorCode::ERR_OK) {
1593 continue;
1594 }
1595 result += currentResult + "\n";
1596 }
1597 if (count == pids.size()) {
1598 TAG_LOGE(AAFwkTag::APPMGR, "no valid pid");
1599 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1600 }
1601 if (result.empty()) {
1602 TAG_LOGE(AAFwkTag::APPMGR, "no ffrt usage is found");
1603 return DumpErrorCode::ERR_INTERNAL_ERROR;
1604 }
1605 return DumpErrorCode::ERR_OK;
1606 }
1607
HandleUserRequestClean(const sptr<IRemoteObject> & abilityToken,pid_t & pid,int32_t & uid)1608 bool AppRunningManager::HandleUserRequestClean(const sptr<IRemoteObject> &abilityToken, pid_t &pid, int32_t &uid)
1609 {
1610 if (abilityToken == nullptr) {
1611 TAG_LOGE(AAFwkTag::APPMGR, "abilityToken is nullptr");
1612 return false;
1613 }
1614
1615 auto appRecord = GetAppRunningRecordByAbilityToken(abilityToken);
1616 if (!appRecord) {
1617 TAG_LOGE(AAFwkTag::APPMGR, "failed to get appRecord.");
1618 return false;
1619 }
1620 if (appRecord->GetSupportProcessCacheState() == SupportProcessCacheState::SUPPORT) {
1621 TAG_LOGI(AAFwkTag::APPMGR, "support process cache should not force clean");
1622 return false;
1623 }
1624
1625 auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(abilityToken);
1626 if (!abilityRecord) {
1627 TAG_LOGE(AAFwkTag::APPMGR, "failed to get abilityRecord.");
1628 return false;
1629 }
1630 abilityRecord->SetUserRequestCleaningStatus();
1631
1632 bool canKill = appRecord->IsAllAbilityReadyToCleanedByUserRequest();
1633 if (!canKill || appRecord->IsKeepAliveApp()) {
1634 return false;
1635 }
1636
1637 appRecord->SetUserRequestCleaning();
1638 if (appRecord->GetPriorityObject()) {
1639 pid = appRecord->GetPriorityObject()->GetPid();
1640 }
1641 uid = appRecord->GetUid();
1642 return true;
1643 }
1644
IsAppProcessesAllCached(const std::string & bundleName,int32_t uid,const std::set<std::shared_ptr<AppRunningRecord>> & cachedSet)1645 bool AppRunningManager::IsAppProcessesAllCached(const std::string &bundleName, int32_t uid,
1646 const std::set<std::shared_ptr<AppRunningRecord>> &cachedSet)
1647 {
1648 if (cachedSet.size() == 0) {
1649 TAG_LOGI(AAFwkTag::APPMGR, "empty cache set.");
1650 return false;
1651 }
1652 std::lock_guard guard(runningRecordMapMutex_);
1653 for (const auto &item : appRunningRecordMap_) {
1654 auto &itemRecord = item.second;
1655 if (itemRecord == nullptr) {
1656 continue;
1657 }
1658 if (itemRecord->GetBundleName() == bundleName && itemRecord->GetUid() == uid) {
1659 auto supportCache =
1660 DelayedSingleton<CacheProcessManager>::GetInstance()->IsAppSupportProcessCache(itemRecord);
1661 // need wait for unsupported processes
1662 if ((cachedSet.find(itemRecord) == cachedSet.end() && supportCache) || !supportCache) {
1663 return false;
1664 }
1665 }
1666 }
1667 return true;
1668 }
1669
UpdateConfigurationDelayed(const std::shared_ptr<AppRunningRecord> & appRecord)1670 int32_t AppRunningManager::UpdateConfigurationDelayed(const std::shared_ptr<AppRunningRecord>& appRecord)
1671 {
1672 std::lock_guard guard(updateConfigurationDelayedLock_);
1673 int32_t result = ERR_OK;
1674 auto it = updateConfigurationDelayedMap_.find(appRecord->GetRecordId());
1675 if (it != updateConfigurationDelayedMap_.end() && it->second) {
1676 int32_t userId = appRecord->GetUid() / BASE_USER_RANGE;
1677 if (userId != 0) {
1678 auto config = multiUserConfigurationMgr_->GetConfigurationByUserId(userId);
1679 std::vector<std::string> diffVe;
1680 configuration_->CompareDifferent(diffVe, config);
1681 configuration_->Merge(diffVe, config);
1682 }
1683 result = appRecord->UpdateConfiguration(*configuration_);
1684 it->second = false;
1685 }
1686 return result;
1687 }
1688
SetMultiUserConfigurationMgr(const std::shared_ptr<MultiUserConfigurationMgr> & multiUserConfigurationMgr)1689 void AppRunningManager::SetMultiUserConfigurationMgr(
1690 const std::shared_ptr<MultiUserConfigurationMgr>& multiUserConfigurationMgr)
1691 {
1692 multiUserConfigurationMgr_ = multiUserConfigurationMgr;
1693 }
1694
CheckAppRunningRecordIsLast(const std::shared_ptr<AppRunningRecord> & appRecord)1695 bool AppRunningManager::CheckAppRunningRecordIsLast(const std::shared_ptr<AppRunningRecord> &appRecord)
1696 {
1697 if (appRecord == nullptr) {
1698 TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
1699 return false;
1700 }
1701 std::lock_guard guard(runningRecordMapMutex_);
1702 if (appRunningRecordMap_.empty()) {
1703 return true;
1704 }
1705 auto uid = appRecord->GetUid();
1706 auto appRecordId = appRecord->GetRecordId();
1707 for (const auto &item : appRunningRecordMap_) {
1708 const auto &itemAppRecord = item.second;
1709 if (itemAppRecord != nullptr &&
1710 itemAppRecord->GetRecordId() != appRecordId &&
1711 itemAppRecord->GetUid() == uid &&
1712 !(appRecord->GetRestartAppFlag())) {
1713 return false;
1714 }
1715 }
1716 return true;
1717 }
1718 } // namespace AppExecFwk
1719 } // namespace OHOS
1720