• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_mgr_service.h"
17 
18 #include <chrono>
19 #include <cstdlib>
20 #include <nlohmann/json.hpp>
21 #include <sys/types.h>
22 #include <thread>
23 
24 #include "ability_manager_errors.h"
25 #include "app_death_recipient.h"
26 #include "app_mgr_constants.h"
27 #include "datetime_ex.h"
28 #include "fd_guard.h"
29 #include "freeze_util.h"
30 #include "global_constant.h"
31 #include "hilog_tag_wrapper.h"
32 #include "hitrace_meter.h"
33 #include "in_process_call_wrapper.h"
34 #include "ipc_skeleton.h"
35 #include "perf_profile.h"
36 #include "permission_constants.h"
37 #include "permission_verification.h"
38 #include "system_ability_definition.h"
39 #include "accesstoken_kit.h"
40 #include "app_mgr_service_const.h"
41 #include "app_mgr_service_dump_error_code.h"
42 #include "cache_process_manager.h"
43 
44 namespace OHOS {
45 namespace AppExecFwk {
46 using AAFwk::FdGuard;
47 constexpr const char* OPTION_KEY_HELP = "-h";
48 constexpr const char* OPTION_KEY_DUMP_IPC = "--ipc";
49 constexpr const char* OPTION_KEY_DUMP_FFRT = "--ffrt";
50 const int32_t HIDUMPER_SERVICE_UID = 1212;
51 constexpr const int INDEX_PID = 1;
52 constexpr const int INDEX_CMD = 2;
53 constexpr const size_t VALID_DUMP_IPC_ARG_SIZE = 3;
54 constexpr const size_t VALID_DUMP_FFRT_ARG_SIZE = 2;
55 constexpr const int MAX_DUMP_FFRT_PID_NUMBER = 3;
56 constexpr const int BASE_TEN = 10;
57 constexpr const char SIGN_TERMINAL = '\0';
58 constexpr int32_t DEFAULT_CONCURRENT_NUMBER = 1;
59 namespace {
60 using namespace std::chrono_literals;
61 constexpr const char* TASK_INIT_APPMGRSERVICEINNER = "InitAppMgrServiceInnerTask";
62 constexpr const char* TASK_ATTACH_APPLICATION = "AttachApplicationTask";
63 constexpr const char* TASK_APPLICATION_FOREGROUNDED = "ApplicationForegroundedTask";
64 constexpr const char* TASK_APPLICATION_BACKGROUNDED = "ApplicationBackgroundedTask";
65 constexpr const char* TASK_APPLICATION_TERMINATED = "ApplicationTerminatedTask";
66 constexpr const char* TASK_ABILITY_CLEANED = "AbilityCleanedTask";
67 constexpr const char* TASK_STARTUP_RESIDENT_PROCESS = "StartupResidentProcess";
68 constexpr const char* TASK_ADD_ABILITY_STAGE_DONE = "AddAbilityStageDone";
69 constexpr const char* TASK_START_USER_TEST_PROCESS = "StartUserTestProcess";
70 constexpr const char* TASK_FINISH_USER_TEST = "FinishUserTest";
71 constexpr const char* TASK_ATTACH_RENDER_PROCESS = "AttachRenderTask";
72 #ifdef SUPPORT_CHILD_PROCESS
73 constexpr const char* TASK_ATTACH_CHILD_PROCESS = "AttachChildProcessTask";
74 constexpr const char* TASK_EXIT_CHILD_PROCESS_SAFELY = "ExitChildProcessSafelyTask";
75 #endif // SUPPORT_CHILD_PROCESS
76 constexpr const char* FOUNDATION_PROCESS = "foundation";
77 constexpr const char* BS_PROCESS_NAME = "bgtaskmgr_service";
78 constexpr int32_t USER_UID = 2000;
79 constexpr const char* HIVIEW_PROCESS_NAME = "hiview";
80 constexpr const char* DEBUG_FROM = "ohos.param.debugFrom";
81 }  // namespace
82 
83 REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true);
84 
AppMgrService()85 AppMgrService::AppMgrService()
86 {
87     appMgrServiceInner_ = std::make_shared<AppMgrServiceInner>();
88     TAG_LOGI(AAFwkTag::APPMGR, "instance created");
89     PerfProfile::GetInstance().SetAmsLoadStartTime(GetTickCount());
90 }
91 
AppMgrService(const int32_t serviceId,bool runOnCreate)92 AppMgrService::AppMgrService(const int32_t serviceId, bool runOnCreate) : SystemAbility(serviceId, runOnCreate)
93 {
94     appMgrServiceInner_ = std::make_shared<AppMgrServiceInner>();
95     TAG_LOGI(AAFwkTag::APPMGR, "instance created");
96     PerfProfile::GetInstance().SetAmsLoadStartTime(GetTickCount());
97 }
98 
~AppMgrService()99 AppMgrService::~AppMgrService()
100 {
101     TAG_LOGI(AAFwkTag::APPMGR, "instance destroyed");
102 }
103 
OnStart()104 void AppMgrService::OnStart()
105 {
106     TAG_LOGI(AAFwkTag::APPMGR, "start service ready");
107     if (appMgrServiceState_.serviceRunningState == ServiceRunningState::STATE_RUNNING) {
108         TAG_LOGW(AAFwkTag::APPMGR, "start service fail");
109         return;
110     }
111 
112     ErrCode errCode = Init();
113     if (FAILED(errCode)) {
114         TAG_LOGE(AAFwkTag::APPMGR, "fail, errCode: %{public}08x", errCode);
115         return;
116     }
117     appMgrServiceState_.serviceRunningState = ServiceRunningState::STATE_RUNNING;
118     if (!AddSystemAbilityListener(WINDOW_MANAGER_SERVICE_ID)) {
119         TAG_LOGE(AAFwkTag::APPMGR, "OnStart, add listener err");
120     }
121     TAG_LOGI(AAFwkTag::APPMGR, "start service success");
122     PerfProfile::GetInstance().SetAmsLoadEndTime(GetTickCount());
123     PerfProfile::GetInstance().Dump();
124 }
125 
OnStop()126 void AppMgrService::OnStop()
127 {
128     TAG_LOGI(AAFwkTag::APPMGR, "stop service ready");
129     appMgrServiceState_.serviceRunningState = ServiceRunningState::STATE_NOT_START;
130     eventHandler_.reset();
131     taskHandler_.reset();
132     if (appMgrServiceInner_) {
133         appMgrServiceInner_->OnStop();
134     }
135     TAG_LOGI(AAFwkTag::APPMGR, "stop service success");
136 }
137 
SetInnerService(const std::shared_ptr<AppMgrServiceInner> & innerService)138 void AppMgrService::SetInnerService(const std::shared_ptr<AppMgrServiceInner> &innerService)
139 {
140     appMgrServiceInner_ = innerService;
141 }
142 
QueryServiceState()143 AppMgrServiceState AppMgrService::QueryServiceState()
144 {
145     if (appMgrServiceInner_) {
146         appMgrServiceState_.connectionState = appMgrServiceInner_->QueryAppSpawnConnectionState();
147     }
148     return appMgrServiceState_;
149 }
150 
Init()151 ErrCode AppMgrService::Init()
152 {
153     TAG_LOGI(AAFwkTag::APPMGR, "init ready");
154     if (!appMgrServiceInner_) {
155         TAG_LOGE(AAFwkTag::APPMGR, "init failed");
156         return ERR_INVALID_OPERATION;
157     }
158 
159     taskHandler_ = AAFwk::TaskHandlerWrap::CreateConcurrentQueueHandler("app_mgr_task_queue",
160         DEFAULT_CONCURRENT_NUMBER);
161     taskHandler_->SetPrintTaskLog(true);
162     eventHandler_ = std::make_shared<AMSEventHandler>(taskHandler_, appMgrServiceInner_);
163     appMgrServiceInner_->SetTaskHandler(taskHandler_);
164     appMgrServiceInner_->SetEventHandler(eventHandler_);
165     DelayedSingleton<CacheProcessManager>::GetInstance()->SetAppMgr(appMgrServiceInner_);
166     std::function<void()> initAppMgrServiceInnerTask = [appMgrServiceInner = appMgrServiceInner_]() {
167         appMgrServiceInner->Init();
168     };
169     taskHandler_->SubmitTask(initAppMgrServiceInnerTask, TASK_INIT_APPMGRSERVICEINNER);
170 
171     ErrCode openErr = appMgrServiceInner_->OpenAppSpawnConnection();
172     if (FAILED(openErr)) {
173         TAG_LOGW(AAFwkTag::APPMGR, "fail, errCode: %{public}08x", openErr);
174     }
175     if (!Publish(this)) {
176         TAG_LOGE(AAFwkTag::APPMGR, " publish fail");
177         return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED;
178     }
179     amsMgrScheduler_ = new (std::nothrow) AmsMgrScheduler(appMgrServiceInner_, taskHandler_);
180     if (!amsMgrScheduler_) {
181         TAG_LOGE(AAFwkTag::APPMGR, "init failed");
182         return ERR_INVALID_OPERATION;
183     }
184     TAG_LOGI(AAFwkTag::APPMGR, "init success");
185     return ERR_OK;
186 }
187 
AttachApplication(const sptr<IRemoteObject> & app)188 void AppMgrService::AttachApplication(const sptr<IRemoteObject> &app)
189 {
190     TAG_LOGD(AAFwkTag::APPMGR, "called");
191     if (!IsReady()) {
192         TAG_LOGE(AAFwkTag::APPMGR, "AttachApplication failed");
193         return;
194     }
195 
196     AbilityRuntime::FreezeUtil::GetInstance().AddAppLifecycleEvent(IPCSkeleton::GetCallingPid(),
197         "AppMgrService::AttachApplication");
198     pid_t pid = IPCSkeleton::GetCallingPid();
199     auto appScheduler = iface_cast<IAppScheduler>(app);
200     if (appScheduler == nullptr) {
201         TAG_LOGE(AAFwkTag::APPMGR, "appScheduler null");
202     }
203     std::function<void()> attachApplicationFunc = [appMgrServiceInner = appMgrServiceInner_, pid, appScheduler]() {
204         appMgrServiceInner->AttachApplication(pid, appScheduler);
205     };
206     taskHandler_->SubmitTask(attachApplicationFunc, AAFwk::TaskAttribute{
207         .taskName_ = TASK_ATTACH_APPLICATION,
208         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
209     });
210 }
211 
PreloadApplication(const std::string & bundleName,int32_t userId,AppExecFwk::PreloadMode preloadMode,int32_t appIndex)212 int32_t AppMgrService::PreloadApplication(const std::string &bundleName, int32_t userId,
213     AppExecFwk::PreloadMode preloadMode, int32_t appIndex)
214 {
215     TAG_LOGD(AAFwkTag::APPMGR, "PreloadApplication called");
216     if (!IsReady()) {
217         TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication failed");
218         return ERR_INVALID_OPERATION;
219     }
220     return appMgrServiceInner_->PreloadApplication(bundleName, userId, preloadMode, appIndex);
221 }
222 
ApplicationForegrounded(const int32_t recordId)223 void AppMgrService::ApplicationForegrounded(const int32_t recordId)
224 {
225     if (!IsReady()) {
226         return;
227     }
228     if (!JudgeAppSelfCalled(recordId)) {
229         return;
230     }
231     AbilityRuntime::FreezeUtil::GetInstance().AddAppLifecycleEvent(IPCSkeleton::GetCallingPid(),
232         "AppMgrService::AppForegrounded");
233     std::function<void()> applicationForegroundedFunc = [appMgrServiceInner = appMgrServiceInner_, recordId]() {
234         appMgrServiceInner->ApplicationForegrounded(recordId);
235     };
236     taskHandler_->SubmitTask(applicationForegroundedFunc, AAFwk::TaskAttribute{
237         .taskName_ = TASK_APPLICATION_FOREGROUNDED,
238         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
239     });
240 }
241 
ApplicationBackgrounded(const int32_t recordId)242 void AppMgrService::ApplicationBackgrounded(const int32_t recordId)
243 {
244     if (!IsReady()) {
245         return;
246     }
247     if (!JudgeAppSelfCalled(recordId)) {
248         return;
249     }
250     AbilityRuntime::FreezeUtil::GetInstance().AddAppLifecycleEvent(IPCSkeleton::GetCallingPid(),
251         "AppMgrService::AppBackgrounded");
252     taskHandler_->CancelTask("appbackground_" + std::to_string(recordId));
253     std::function<void()> applicationBackgroundedFunc = [appMgrServiceInner = appMgrServiceInner_, recordId]() {
254         appMgrServiceInner->ApplicationBackgrounded(recordId);
255     };
256     taskHandler_->SubmitTask(applicationBackgroundedFunc, AAFwk::TaskAttribute{
257         .taskName_ = TASK_APPLICATION_BACKGROUNDED,
258         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
259     });
260 }
261 
ApplicationTerminated(const int32_t recordId)262 void AppMgrService::ApplicationTerminated(const int32_t recordId)
263 {
264     if (!IsReady()) {
265         return;
266     }
267     if (!JudgeAppSelfCalled(recordId)) {
268         return;
269     }
270     std::function<void()> applicationTerminatedFunc = [appMgrServiceInner = appMgrServiceInner_, recordId]() {
271         appMgrServiceInner->ApplicationTerminated(recordId);
272     };
273     taskHandler_->SubmitTask(applicationTerminatedFunc, AAFwk::TaskAttribute{
274         .taskName_ = TASK_APPLICATION_TERMINATED,
275         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
276     });
277 }
278 
AbilityCleaned(const sptr<IRemoteObject> & token)279 void AppMgrService::AbilityCleaned(const sptr<IRemoteObject> &token)
280 {
281     if (!IsReady()) {
282         return;
283     }
284 
285     auto callerUid = IPCSkeleton::GetCallingUid();
286     auto appRecord = appMgrServiceInner_->GetTerminatingAppRunningRecord(token);
287     if (!appRecord || appRecord->GetUid() != callerUid) {
288         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
289         return;
290     }
291 
292     std::function<void()> abilityCleanedFunc = [appMgrServiceInner = appMgrServiceInner_, token]() {
293         appMgrServiceInner->AbilityTerminated(token);
294     };
295     taskHandler_->SubmitTask(abilityCleanedFunc, AAFwk::TaskAttribute{
296         .taskName_ = TASK_ABILITY_CLEANED,
297         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
298     });
299 }
300 
IsReady() const301 bool AppMgrService::IsReady() const
302 {
303     if (appMgrServiceInner_ && taskHandler_ && eventHandler_) {
304         return true;
305     }
306 
307     TAG_LOGW(AAFwkTag::APPMGR, "not ready");
308     return false;
309 }
310 
StartupResidentProcess(const std::vector<AppExecFwk::BundleInfo> & bundleInfos)311 void AppMgrService::StartupResidentProcess(const std::vector<AppExecFwk::BundleInfo> &bundleInfos)
312 {
313     if (!IsReady()) {
314         return;
315     }
316     pid_t callingPid = IPCSkeleton::GetCallingPid();
317     pid_t pid = getprocpid();
318     if (callingPid != pid) {
319         TAG_LOGE(AAFwkTag::APPMGR, "not process call");
320         return;
321     }
322     TAG_LOGI(AAFwkTag::APPMGR, "start process");
323     std::function <void()> startupResidentProcess = [appMgrServiceInner = appMgrServiceInner_, bundleInfos]() {
324         appMgrServiceInner->LoadResidentProcess(bundleInfos);
325     };
326     taskHandler_->SubmitTask(startupResidentProcess, AAFwk::TaskAttribute{
327         .taskName_ = TASK_STARTUP_RESIDENT_PROCESS,
328         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
329     });
330 }
331 
GetAmsMgr()332 sptr<IAmsMgr> AppMgrService::GetAmsMgr()
333 {
334     return amsMgrScheduler_;
335 }
336 
ClearUpApplicationData(const std::string & bundleName,int32_t appCloneIndex,int32_t userId)337 int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName, int32_t appCloneIndex, int32_t userId)
338 {
339     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
340         TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA");
341         return AAFwk::ERR_NOT_SYSTEM_APP;
342     }
343     if (!IsReady()) {
344         return ERR_INVALID_OPERATION;
345     }
346     std::shared_ptr<RemoteClientManager> remoteClientManager = std::make_shared<RemoteClientManager>();
347     if (remoteClientManager == nullptr) {
348         TAG_LOGE(AAFwkTag::APPMGR, "null remoteClientManager");
349         return ERR_INVALID_OPERATION;
350     }
351     auto bundleMgrHelper = remoteClientManager->GetBundleManagerHelper();
352     if (bundleMgrHelper == nullptr) {
353         TAG_LOGE(AAFwkTag::APPMGR, "null bundleMgrHelper");
354         return ERR_INVALID_OPERATION;
355     }
356     int32_t callingUid = IPCSkeleton::GetCallingUid();
357     if ((callingUid != 0 && callingUid != USER_UID) || userId < 0) {
358         std::string callerBundleName;
359         auto result = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
360         if (result != ERR_OK) {
361             TAG_LOGE(AAFwkTag::APPMGR, "getBundleName failed: %{public}d", result);
362             return ERR_INVALID_OPERATION;
363         }
364         auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
365             AAFwk::PermissionConstants::PERMISSION_CLEAN_APPLICATION_DATA);
366         if (!isCallingPerm) {
367             TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
368             return AAFwk::CHECK_PERMISSION_FAILED;
369         }
370     }
371     if (appCloneIndex < 0 || appCloneIndex > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
372         TAG_LOGE(AAFwkTag::APPMGR, "appCloneIndex invalid");
373         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
374     }
375     pid_t pid = IPCSkeleton::GetCallingPid();
376     return appMgrServiceInner_->ClearUpApplicationData(bundleName, callingUid, pid, appCloneIndex, userId);
377 }
378 
ClearUpApplicationDataBySelf(int32_t userId)379 int32_t AppMgrService::ClearUpApplicationDataBySelf(int32_t userId)
380 {
381     if (!IsReady()) {
382         return ERR_INVALID_OPERATION;
383     }
384     int32_t uid = IPCSkeleton::GetCallingUid();
385     pid_t pid = IPCSkeleton::GetCallingPid();
386     return appMgrServiceInner_->ClearUpApplicationDataBySelf(uid, pid, userId);
387 }
388 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)389 int32_t AppMgrService::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
390 {
391     if (!IsReady()) {
392         return ERR_INVALID_OPERATION;
393     }
394     return appMgrServiceInner_->GetAllRunningProcesses(info);
395 }
396 
GetRunningMultiAppInfoByBundleName(const std::string & bundleName,RunningMultiAppInfo & info)397 int32_t AppMgrService::GetRunningMultiAppInfoByBundleName(const std::string &bundleName,
398     RunningMultiAppInfo &info)
399 {
400     if (!IsReady()) {
401         return ERR_INVALID_OPERATION;
402     }
403 
404     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
405         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not SA");
406         return ERR_INVALID_OPERATION;
407     }
408 
409     bool isCallingPermission = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
410     if (!isCallingPermission) {
411         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
412         return ERR_PERMISSION_DENIED;
413     }
414     return appMgrServiceInner_->GetRunningMultiAppInfoByBundleName(bundleName, info);
415 }
416 
GetAllRunningInstanceKeysBySelf(std::vector<std::string> & instanceKeys)417 int32_t AppMgrService::GetAllRunningInstanceKeysBySelf(std::vector<std::string> &instanceKeys)
418 {
419     if (!IsReady()) {
420         return ERR_INVALID_OPERATION;
421     }
422     return appMgrServiceInner_->GetAllRunningInstanceKeysBySelf(instanceKeys);
423 }
424 
GetAllRunningInstanceKeysByBundleName(const std::string & bundleName,std::vector<std::string> & instanceKeys,int32_t userId)425 int32_t AppMgrService::GetAllRunningInstanceKeysByBundleName(const std::string &bundleName,
426     std::vector<std::string> &instanceKeys, int32_t userId)
427 {
428     if (!IsReady()) {
429         return ERR_INVALID_OPERATION;
430     }
431     return appMgrServiceInner_->GetAllRunningInstanceKeysByBundleName(bundleName, instanceKeys, userId);
432 }
433 
GetRunningProcessesByBundleType(BundleType bundleType,std::vector<RunningProcessInfo> & info)434 int32_t AppMgrService::GetRunningProcessesByBundleType(BundleType bundleType,
435     std::vector<RunningProcessInfo> &info)
436 {
437     if (!IsReady()) {
438         return ERR_INVALID_OPERATION;
439     }
440     return appMgrServiceInner_->GetRunningProcessesByBundleType(bundleType, info);
441 }
442 
GetAllRenderProcesses(std::vector<RenderProcessInfo> & info)443 int32_t AppMgrService::GetAllRenderProcesses(std::vector<RenderProcessInfo> &info)
444 {
445     if (!IsReady()) {
446         return ERR_INVALID_OPERATION;
447     }
448     return appMgrServiceInner_->GetAllRenderProcesses(info);
449 }
450 
GetAllChildrenProcesses(std::vector<ChildProcessInfo> & info)451 int AppMgrService::GetAllChildrenProcesses(std::vector<ChildProcessInfo> &info)
452 {
453 #ifdef SUPPORT_CHILD_PROCESS
454     if (!IsReady()) {
455         return ERR_INVALID_OPERATION;
456     }
457     return appMgrServiceInner_->GetAllChildrenProcesses(info);
458 #endif // SUPPORT_CHILD_PROCESS
459     return ERR_INVALID_OPERATION;
460 }
461 
JudgeSandboxByPid(pid_t pid,bool & isSandbox)462 int32_t AppMgrService::JudgeSandboxByPid(pid_t pid, bool &isSandbox)
463 {
464     if (!IsReady()) {
465         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
466         return ERR_INVALID_OPERATION;
467     }
468     bool isCallingPermission =
469         AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS);
470     if (!isCallingPermission) {
471         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
472         return ERR_PERMISSION_DENIED;
473     }
474     auto appRunningRecord = appMgrServiceInner_->GetAppRunningRecordByPid(pid);
475     if (appRunningRecord && appRunningRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
476         isSandbox = true;
477         TAG_LOGD(AAFwkTag::APPMGR, "current app is a sandbox.");
478         return ERR_OK;
479     }
480     TAG_LOGD(AAFwkTag::APPMGR, "current app is not a sandbox.");
481     return ERR_OK;
482 }
483 
IsTerminatingByPid(pid_t pid,bool & isTerminating)484 int32_t AppMgrService::IsTerminatingByPid(pid_t pid, bool &isTerminating)
485 {
486     if (!IsReady()) {
487         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
488         return ERR_INVALID_OPERATION;
489     }
490     bool isCallingPermission =
491         AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS);
492     if (!isCallingPermission) {
493         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
494         return ERR_PERMISSION_DENIED;
495     }
496     auto appRunningRecord = appMgrServiceInner_->GetAppRunningRecordByPid(pid);
497     if (appRunningRecord && appRunningRecord->IsTerminating()) {
498         isTerminating = true;
499         TAG_LOGD(AAFwkTag::APPMGR, "current pid %{public}d is terminating.", pid);
500         return ERR_OK;
501     }
502     TAG_LOGD(AAFwkTag::APPMGR, "current pid %{public}d is not terminating.", pid);
503     return ERR_OK;
504 }
505 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)506 int32_t AppMgrService::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
507 {
508     if (!IsReady()) {
509         return ERR_INVALID_OPERATION;
510     }
511     return appMgrServiceInner_->GetProcessRunningInfosByUserId(info, userId);
512 }
513 
GetProcessRunningInformation(RunningProcessInfo & info)514 int32_t AppMgrService::GetProcessRunningInformation(RunningProcessInfo &info)
515 {
516     if (!IsReady()) {
517         return ERR_INVALID_OPERATION;
518     }
519     return appMgrServiceInner_->GetProcessRunningInformation(info);
520 }
521 
NotifyMemoryLevel(int32_t level)522 int32_t AppMgrService::NotifyMemoryLevel(int32_t level)
523 {
524     if (!IsReady()) {
525         return ERR_INVALID_OPERATION;
526     }
527     return appMgrServiceInner_->NotifyMemoryLevel(level);
528 }
529 
NotifyProcMemoryLevel(const std::map<pid_t,MemoryLevel> & procLevelMap)530 int32_t AppMgrService::NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap)
531 {
532     if (!IsReady()) {
533         return ERR_INVALID_OPERATION;
534     }
535     return appMgrServiceInner_->NotifyProcMemoryLevel(procLevelMap);
536 }
537 
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)538 int32_t AppMgrService::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
539 {
540     if (!IsReady()) {
541         return ERR_INVALID_OPERATION;
542     }
543     return appMgrServiceInner_->DumpHeapMemory(pid, mallocInfo);
544 }
545 
546 // Authenticate dump permissions
HasDumpPermission() const547 bool AppMgrService::HasDumpPermission() const
548 {
549     uint32_t callingTokenID = IPCSkeleton::GetCallingTokenID();
550     int res = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callingTokenID, "ohos.permission.DUMP");
551     if (res != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
552         TAG_LOGE(AAFwkTag::APPMGR, "no permission");
553         return false;
554     }
555     return true;
556 }
557 
DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)558 int32_t AppMgrService::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
559 {
560     if (!IsReady() || !HasDumpPermission()) {
561         return ERR_INVALID_OPERATION;
562     }
563     return appMgrServiceInner_->DumpJsHeapMemory(info);
564 }
565 
AddAbilityStageDone(const int32_t recordId)566 void AppMgrService::AddAbilityStageDone(const int32_t recordId)
567 {
568     if (!IsReady()) {
569         return;
570     }
571     if (!JudgeAppSelfCalled(recordId)) {
572         return;
573     }
574     std::function <void()> addAbilityStageDone = [appMgrServiceInner = appMgrServiceInner_, recordId]() {
575         appMgrServiceInner->AddAbilityStageDone(recordId);
576     };
577     taskHandler_->SubmitTask(addAbilityStageDone, AAFwk::TaskAttribute{
578         .taskName_ = TASK_ADD_ABILITY_STAGE_DONE,
579         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
580     });
581 }
582 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)583 int32_t AppMgrService::RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer,
584     const std::vector<std::string> &bundleNameList)
585 {
586     TAG_LOGD(AAFwkTag::APPMGR, "begin");
587     if (!IsReady()) {
588         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
589         return ERR_INVALID_OPERATION;
590     }
591     return appMgrServiceInner_->RegisterApplicationStateObserver(observer, bundleNameList);
592 }
593 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)594 int32_t AppMgrService::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
595 {
596     TAG_LOGD(AAFwkTag::APPMGR, "begin");
597     if (!IsReady()) {
598         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
599         return ERR_INVALID_OPERATION;
600     }
601     return appMgrServiceInner_->UnregisterApplicationStateObserver(observer);
602 }
603 
RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)604 int32_t AppMgrService::RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> &observer)
605 {
606     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
607     TAG_LOGD(AAFwkTag::APPMGR, "called");
608     if (!IsReady()) {
609         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
610         return ERR_INVALID_OPERATION;
611     }
612     return appMgrServiceInner_->RegisterAbilityForegroundStateObserver(observer);
613 }
614 
UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)615 int32_t AppMgrService::UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> &observer)
616 {
617     TAG_LOGD(AAFwkTag::APPMGR, "called");
618     if (!IsReady()) {
619         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
620         return ERR_INVALID_OPERATION;
621     }
622     return appMgrServiceInner_->UnregisterAbilityForegroundStateObserver(observer);
623 }
624 
GetForegroundApplications(std::vector<AppStateData> & list)625 int32_t AppMgrService::GetForegroundApplications(std::vector<AppStateData> &list)
626 {
627     TAG_LOGD(AAFwkTag::APPMGR, "begin");
628     if (!IsReady()) {
629         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
630         return ERR_INVALID_OPERATION;
631     }
632     return appMgrServiceInner_->GetForegroundApplications(list);
633 }
634 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const AppExecFwk::BundleInfo & bundleInfo,int32_t userId)635 int AppMgrService::StartUserTestProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
636     const AppExecFwk::BundleInfo &bundleInfo, int32_t userId)
637 {
638     if (!IsReady()) {
639         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
640         return ERR_INVALID_OPERATION;
641     }
642     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
643         TAG_LOGE(AAFwkTag::APPMGR, "StartUserTestProcess is not shell call");
644         return ERR_INVALID_OPERATION;
645     }
646     std::function<void()> startUserTestProcessFunc = [appMgrServiceInner = appMgrServiceInner_,
647         want, observer, bundleInfo, userId]() {
648         appMgrServiceInner->StartUserTestProcess(want, observer, bundleInfo, userId);
649     };
650     taskHandler_->SubmitTask(startUserTestProcessFunc, TASK_START_USER_TEST_PROCESS);
651     return ERR_OK;
652 }
653 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)654 int AppMgrService::FinishUserTest(const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
655 {
656     if (!IsReady()) {
657         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
658         return ERR_INVALID_OPERATION;
659     }
660     std::shared_ptr<RemoteClientManager> remoteClientManager = std::make_shared<RemoteClientManager>();
661     if (remoteClientManager == nullptr) {
662         TAG_LOGE(AAFwkTag::APPMGR, "null remoteClientManager");
663         return ERR_INVALID_OPERATION;
664     }
665     auto bundleMgrHelper = remoteClientManager->GetBundleManagerHelper();
666     if (bundleMgrHelper == nullptr) {
667         TAG_LOGE(AAFwkTag::APPMGR, "null bundleMgrHelper");
668         return ERR_INVALID_OPERATION;
669     }
670     int32_t callingUid = IPCSkeleton::GetCallingUid();
671     std::string callerBundleName;
672     auto result = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
673     if (result == ERR_OK) {
674         TAG_LOGI(AAFwkTag::APPMGR, "callingPid_ %{public}s", callerBundleName.c_str());
675         if (bundleName != callerBundleName) {
676             TAG_LOGE(AAFwkTag::APPMGR, "not process call");
677             return ERR_INVALID_OPERATION;
678         }
679     } else {
680         TAG_LOGE(AAFwkTag::APPMGR, "fail: %{public}d", result);
681         return ERR_INVALID_OPERATION;
682     }
683     pid_t callingPid = IPCSkeleton::GetCallingPid();
684     std::function<void()> finishUserTestProcessFunc = [appMgrServiceInner = appMgrServiceInner_, msg,
685         resultCode, bundleName, callingPid]() {
686         appMgrServiceInner->FinishUserTest(msg, resultCode, bundleName, callingPid);
687     };
688     taskHandler_->SubmitTask(finishUserTestProcessFunc, TASK_FINISH_USER_TEST);
689     return ERR_OK;
690 }
691 
Dump(int fd,const std::vector<std::u16string> & args)692 int AppMgrService::Dump(int fd, const std::vector<std::u16string>& args)
693 {
694     TAG_LOGD(AAFwkTag::APPMGR, "called");
695     if (!IsReady()) {
696         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
697         return ERR_APPEXECFWK_HIDUMP_ERROR;
698     }
699 
700     std::string result;
701     auto errCode = Dump(args, result);
702     int ret = dprintf(fd, "%s\n", result.c_str());
703     if (ret < 0) {
704         TAG_LOGE(AAFwkTag::APPMGR, "dprintf error");
705         return ERR_APPEXECFWK_HIDUMP_ERROR;
706     }
707     return errCode;
708 }
709 
Dump(const std::vector<std::u16string> & args,std::string & result)710 int AppMgrService::Dump(const std::vector<std::u16string>& args, std::string& result)
711 {
712     TAG_LOGD(AAFwkTag::APPMGR, "called");
713     auto size = args.size();
714     if (size == 0) {
715         return ShowHelp(args, result);
716     }
717 
718     std::string optionKey = Str16ToStr8(args[0]);
719     if (optionKey == OPTION_KEY_HELP) {
720         return ShowHelp(args, result);
721     }
722     if (optionKey == OPTION_KEY_DUMP_IPC) {
723         return DumpIpc(args, result);
724     }
725     if (optionKey == OPTION_KEY_DUMP_FFRT) {
726         return DumpFfrt(args, result);
727     }
728     result.append("error: unkown option.\n");
729     TAG_LOGE(AAFwkTag::APPMGR, "option key %{public}s does not exist", optionKey.c_str());
730     return DumpErrorCode::ERR_UNKNOWN_OPTION_ERROR;
731 }
732 
ShowHelp(const std::vector<std::u16string> & args,std::string & result)733 int AppMgrService::ShowHelp(const std::vector<std::u16string>& args, std::string& result)
734 {
735     result.append("Usage:\n")
736         .append("-h                          ")
737         .append("help text for the tool\n")
738         .append("--ffrt pid1[,pid2,pid3]     ")
739         .append("dump ffrt info\n");
740 
741     return ERR_OK;
742 }
743 
DumpIpcAllInner(const AppMgrService::DumpIpcKey key,std::string & result)744 int AppMgrService::DumpIpcAllInner(const AppMgrService::DumpIpcKey key, std::string& result)
745 {
746     TAG_LOGI(AAFwkTag::APPMGR, "call");
747     switch (key) {
748         case KEY_DUMP_IPC_START:
749             return DumpIpcAllStart(result);
750         case KEY_DUMP_IPC_STOP:
751             return DumpIpcAllStop(result);
752         case KEY_DUMP_IPC_STAT:
753             return DumpIpcAllStat(result);
754         default: {
755             result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
756                 .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
757             TAG_LOGE(AAFwkTag::APPMGR, "dump ipc all function does not exist");
758             return DumpErrorCode::ERR_INTERNAL_ERROR;
759         }
760     }
761 }
762 
DumpIpcWithPidInner(const AppMgrService::DumpIpcKey key,const std::string & optionPid,std::string & result)763 int AppMgrService::DumpIpcWithPidInner(const AppMgrService::DumpIpcKey key,
764     const std::string& optionPid, std::string& result)
765 {
766     TAG_LOGI(AAFwkTag::APPMGR, "call");
767     int32_t pid = -1;
768     char* end = nullptr;
769     pid = static_cast<int32_t>(std::strtol(optionPid.c_str(), &end, BASE_TEN));
770     if (end && *end != SIGN_TERMINAL) {
771         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
772             .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
773         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}s", optionPid.c_str());
774         return DumpErrorCode::ERR_INVALID_PID_ERROR;
775     }
776     if (pid < 0) {
777         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
778             .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
779         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}s", optionPid.c_str());
780         return DumpErrorCode::ERR_INVALID_PID_ERROR;
781     }
782 
783     switch (key) {
784         case KEY_DUMP_IPC_START:
785             return DumpIpcStart(pid, result);
786         case KEY_DUMP_IPC_STOP:
787             return DumpIpcStop(pid, result);
788         case KEY_DUMP_IPC_STAT:
789             return DumpIpcStat(pid, result);
790         default: {
791             TAG_LOGE(AAFwkTag::APPMGR, "option key %{public}d does not exist", key);
792             result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
793                 .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
794             TAG_LOGE(AAFwkTag::APPMGR, "dump ipc function does not exist");
795             return DumpErrorCode::ERR_INTERNAL_ERROR;
796         }
797     }
798 }
799 
DumpFfrtInner(const std::string & pidsRaw,std::string & result)800 int AppMgrService::DumpFfrtInner(const std::string& pidsRaw, std::string& result)
801 {
802     TAG_LOGI(AAFwkTag::APPMGR, "call");
803     std::vector<std::string> pidsStr;
804     SplitStr(pidsRaw, ",", pidsStr);
805     if (pidsStr.empty()) {
806         TAG_LOGE(AAFwkTag::APPMGR, "pids are empty");
807         return DumpErrorCode::ERR_INVALID_PID_ERROR;
808     }
809     if (pidsStr.size() > MAX_DUMP_FFRT_PID_NUMBER) {
810         pidsStr.resize(MAX_DUMP_FFRT_PID_NUMBER);
811     }
812     std::vector<int32_t> pids;
813     for (const auto& pidStr : pidsStr) {
814         int pid = -1;
815         char* end = nullptr;
816         pid = static_cast<int32_t>(std::strtol(pidStr.c_str(), &end, BASE_TEN));
817         if (end && *end != SIGN_TERMINAL) {
818             TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}s", pidStr.c_str());
819             continue;
820         }
821         if (pid < 0) {
822             TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}s", pidStr.c_str());
823             continue;
824         }
825         TAG_LOGD(AAFwkTag::APPMGR, "valid pid:%{public}d", pid);
826         pids.push_back(pid);
827     }
828     TAG_LOGD(AAFwkTag::APPMGR, "number of valid pids:%{public}d", static_cast<int>(pids.size()));
829     if (pids.empty()) {
830         TAG_LOGE(AAFwkTag::APPMGR, "pids are empty");
831         return DumpErrorCode::ERR_INVALID_PID_ERROR;
832     }
833     return appMgrServiceInner_->DumpFfrt(pids, result);
834 }
835 
GetDumpIpcKeyByOption(const std::string & option,DumpIpcKey & key)836 bool AppMgrService::GetDumpIpcKeyByOption(const std::string &option, DumpIpcKey &key)
837 {
838     if (option == "--start-stat") {
839         key = KEY_DUMP_IPC_START;
840         return true;
841     }
842     if (option == "--stop-stat") {
843         key = KEY_DUMP_IPC_STOP;
844         return true;
845     }
846     if (option == "--stat") {
847         key = KEY_DUMP_IPC_STAT;
848         return true;
849     }
850     return false;
851 }
852 
DumpIpc(const std::vector<std::u16string> & args,std::string & result)853 int AppMgrService::DumpIpc(const std::vector<std::u16string>& args, std::string& result)
854 {
855     TAG_LOGD(AAFwkTag::APPMGR, "Called. AppMgrService::DumpIpc start");
856     if (args.size() != VALID_DUMP_IPC_ARG_SIZE) {
857         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
858             .append(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS, strlen(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS));
859         TAG_LOGE(AAFwkTag::APPMGR, "invalid arguments");
860         return DumpErrorCode::ERR_INVALID_NUM_ARGS_ERROR;
861     }
862     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
863     if (!isHidumperServiceCall) {
864         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
865             .append(MSG_DUMP_FAIL_REASON_PERMISSION_DENY, strlen(MSG_DUMP_FAIL_REASON_PERMISSION_DENY));
866         TAG_LOGE(AAFwkTag::APPMGR, "permission deny");
867         return DumpErrorCode::ERR_PERMISSION_DENY_ERROR;
868     }
869 
870     std::string optionCmd = Str16ToStr8(args[INDEX_CMD]);
871     std::string optionPid = Str16ToStr8(args[INDEX_PID]);
872     TAG_LOGD(AAFwkTag::APPMGR, "option pid:%{public}s, option cmd:%{public}s",
873         optionPid.c_str(), optionCmd.c_str());
874 
875     DumpIpcKey key;
876     if (!GetDumpIpcKeyByOption(optionCmd, key)) {
877         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
878             .append(MSG_DUMP_FAIL_REASON_INVALILD_CMD, strlen(MSG_DUMP_FAIL_REASON_INVALILD_CMD));
879         TAG_LOGE(AAFwkTag::APPMGR, "option command %{public}s does not exist", optionCmd.c_str());
880         return DumpErrorCode::ERR_INVALID_CMD_ERROR;
881     }
882 
883     if (optionPid == "-a" || optionPid == "all" || optionPid == "--all") {
884         return DumpIpcAllInner(key, result);
885     }
886     return DumpIpcWithPidInner(key, optionPid, result);
887 }
888 
DumpFfrt(const std::vector<std::u16string> & args,std::string & result)889 int AppMgrService::DumpFfrt(const std::vector<std::u16string>& args, std::string& result)
890 {
891     TAG_LOGD(AAFwkTag::APPMGR, "Called. AppMgrService::DumpFfrt start");
892     if (args.size() != VALID_DUMP_FFRT_ARG_SIZE) {
893         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
894             .append(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS, strlen(MSG_DUMP_FAIL_REASON_INVALILD_NUM_ARGS));
895         TAG_LOGE(AAFwkTag::APPMGR, "invalid arguments");
896         return DumpErrorCode::ERR_INVALID_NUM_ARGS_ERROR;
897     }
898     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
899     if (!isHidumperServiceCall) {
900         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
901             .append(MSG_DUMP_FAIL_REASON_PERMISSION_DENY, strlen(MSG_DUMP_FAIL_REASON_PERMISSION_DENY));
902         TAG_LOGE(AAFwkTag::APPMGR, "permission deny");
903         return DumpErrorCode::ERR_PERMISSION_DENY_ERROR;
904     }
905 
906     std::string pidsRaw = Str16ToStr8(args[INDEX_PID]);
907     TAG_LOGD(AAFwkTag::APPMGR, "pids:%{public}s", pidsRaw.c_str());
908 
909     return DumpFfrtInner(pidsRaw, result);
910 }
911 
DumpIpcAllStart(std::string & result)912 int AppMgrService::DumpIpcAllStart(std::string& result)
913 {
914     TAG_LOGD(AAFwkTag::APPMGR, "called");
915     return appMgrServiceInner_->DumpIpcAllStart(result);
916 }
917 
DumpIpcAllStop(std::string & result)918 int AppMgrService::DumpIpcAllStop(std::string& result)
919 {
920     TAG_LOGD(AAFwkTag::APPMGR, "called");
921     return appMgrServiceInner_->DumpIpcAllStop(result);
922 }
923 
DumpIpcAllStat(std::string & result)924 int AppMgrService::DumpIpcAllStat(std::string& result)
925 {
926     TAG_LOGD(AAFwkTag::APPMGR, "called");
927     return appMgrServiceInner_->DumpIpcAllStat(result);
928 }
929 
DumpIpcStart(const int32_t pid,std::string & result)930 int AppMgrService::DumpIpcStart(const int32_t pid, std::string& result)
931 {
932     TAG_LOGD(AAFwkTag::APPMGR, "called");
933     return appMgrServiceInner_->DumpIpcStart(pid, result);
934 }
935 
DumpIpcStop(const int32_t pid,std::string & result)936 int AppMgrService::DumpIpcStop(const int32_t pid, std::string& result)
937 {
938     TAG_LOGD(AAFwkTag::APPMGR, "called");
939     return appMgrServiceInner_->DumpIpcStop(pid, result);
940 }
941 
DumpIpcStat(const int32_t pid,std::string & result)942 int AppMgrService::DumpIpcStat(const int32_t pid, std::string& result)
943 {
944     TAG_LOGD(AAFwkTag::APPMGR, "called");
945     return appMgrServiceInner_->DumpIpcStat(pid, result);
946 }
947 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)948 void AppMgrService::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
949 {
950     if (!IsReady()) {
951         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
952         return;
953     }
954     if (!JudgeAppSelfCalled(recordId)) {
955         return;
956     }
957     auto task = [appMgrServiceInner = appMgrServiceInner_, recordId, want, flag]() {
958         appMgrServiceInner->ScheduleAcceptWantDone(recordId, want, flag);
959     };
960     taskHandler_->SubmitTask(task, "ScheduleAcceptWantDone");
961 }
962 
ScheduleNewProcessRequestDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)963 void AppMgrService::ScheduleNewProcessRequestDone(const int32_t recordId, const AAFwk::Want &want,
964     const std::string &flag)
965 {
966     if (!IsReady()) {
967         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
968         return;
969     }
970     if (!JudgeAppSelfCalled(recordId)) {
971         return;
972     }
973     auto task = [appMgrServiceInner = appMgrServiceInner_, recordId, want, flag]() {
974         appMgrServiceInner->ScheduleNewProcessRequestDone(recordId, want, flag);
975     };
976     taskHandler_->SubmitTask(task, AAFwk::TaskAttribute{
977         .taskName_ = "ScheduleNewProcessRequestDone",
978         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
979     });
980 }
981 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)982 int AppMgrService::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
983 {
984     if (!IsReady()) {
985         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
986         return ERR_INVALID_OPERATION;
987     }
988     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
989     if (!isSaCall) {
990         TAG_LOGE(AAFwkTag::APPMGR, "null Sacall");
991         return ERR_INVALID_OPERATION;
992     }
993     return appMgrServiceInner_->GetAbilityRecordsByProcessID(pid, tokens);
994 }
995 
PreStartNWebSpawnProcess()996 int32_t AppMgrService::PreStartNWebSpawnProcess()
997 {
998     TAG_LOGI(AAFwkTag::APPMGR, "PreStartNWebSpawnProcess");
999     if (!IsReady()) {
1000         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1001         return ERR_INVALID_OPERATION;
1002     }
1003 
1004     return appMgrServiceInner_->PreStartNWebSpawnProcess(IPCSkeleton::GetCallingPid());
1005 }
1006 
StartRenderProcess(const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,int32_t crashFd,pid_t & renderPid,bool isGPU)1007 int32_t AppMgrService::StartRenderProcess(const std::string &renderParam, int32_t ipcFd,
1008     int32_t sharedFd, int32_t crashFd, pid_t &renderPid, bool isGPU)
1009 {
1010     FdGuard ipcFdGuard(ipcFd);
1011     FdGuard sharedFdGuard(sharedFd);
1012     FdGuard crashFdGuard(crashFd);
1013     if (!IsReady()) {
1014         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1015         return ERR_INVALID_OPERATION;
1016     }
1017 
1018     return appMgrServiceInner_->StartRenderProcess(IPCSkeleton::GetCallingPid(), renderParam,
1019         std::move(ipcFdGuard), std::move(sharedFdGuard), std::move(crashFdGuard), renderPid, isGPU);
1020 }
1021 
AttachRenderProcess(const sptr<IRemoteObject> & scheduler)1022 void AppMgrService::AttachRenderProcess(const sptr<IRemoteObject> &scheduler)
1023 {
1024     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1025     TAG_LOGI(AAFwkTag::APPMGR, "AttachRenderProcess");
1026     if (!IsReady()) {
1027         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1028         return;
1029     }
1030 
1031     auto pid = IPCSkeleton::GetCallingPid();
1032     auto fun = [appMgrServiceInner = appMgrServiceInner_, pid, scheduler]() {
1033         appMgrServiceInner->AttachRenderProcess(pid, iface_cast<IRenderScheduler>(scheduler));
1034     };
1035     taskHandler_->SubmitTask(fun, AAFwk::TaskAttribute{
1036         .taskName_ = TASK_ATTACH_RENDER_PROCESS,
1037         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
1038     });
1039 }
1040 
SaveBrowserChannel(sptr<IRemoteObject> browser)1041 void AppMgrService::SaveBrowserChannel(sptr<IRemoteObject> browser)
1042 {
1043     if (!IsReady()) {
1044         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1045         return;
1046     }
1047 
1048     appMgrServiceInner_->SaveBrowserChannel(IPCSkeleton::GetCallingPid(), browser);
1049 }
1050 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)1051 int32_t AppMgrService::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
1052 {
1053     if (!IsReady()) {
1054         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1055         return ERR_INVALID_OPERATION;
1056     }
1057 
1058     return appMgrServiceInner_->GetRenderProcessTerminationStatus(renderPid, status);
1059 }
1060 
GetConfiguration(Configuration & config)1061 int32_t AppMgrService::GetConfiguration(Configuration& config)
1062 {
1063     if (!IsReady()) {
1064         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1065         return ERR_INVALID_OPERATION;
1066     }
1067     config = *(appMgrServiceInner_->GetConfiguration());
1068     return ERR_OK;
1069 }
1070 
UpdateConfiguration(const Configuration & config,const int32_t userId)1071 int32_t AppMgrService::UpdateConfiguration(const Configuration& config, const int32_t userId)
1072 {
1073     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1074     if (!IsReady()) {
1075         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1076         return ERR_INVALID_OPERATION;
1077     }
1078     return appMgrServiceInner_->UpdateConfiguration(config, userId);
1079 }
1080 
UpdateConfigurationByBundleName(const Configuration & config,const std::string & name,int32_t appIndex)1081 int32_t AppMgrService::UpdateConfigurationByBundleName(const Configuration& config, const std::string &name,
1082     int32_t appIndex)
1083 {
1084     if (!IsReady()) {
1085         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1086         return ERR_INVALID_OPERATION;
1087     }
1088     return appMgrServiceInner_->UpdateConfigurationByBundleName(config, name, appIndex);
1089 }
1090 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)1091 int32_t AppMgrService::RegisterConfigurationObserver(const sptr<IConfigurationObserver> &observer)
1092 {
1093     if (!IsReady()) {
1094         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1095         return ERR_INVALID_OPERATION;
1096     }
1097     return appMgrServiceInner_->RegisterConfigurationObserver(observer);
1098 }
1099 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)1100 int32_t AppMgrService::UnregisterConfigurationObserver(const sptr<IConfigurationObserver> &observer)
1101 {
1102     if (!IsReady()) {
1103         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1104         return ERR_INVALID_OPERATION;
1105     }
1106     return appMgrServiceInner_->UnregisterConfigurationObserver(observer);
1107 }
1108 
GetAppRunningStateByBundleName(const std::string & bundleName)1109 bool AppMgrService::GetAppRunningStateByBundleName(const std::string &bundleName)
1110 {
1111     if (!IsReady()) {
1112         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1113         return false;
1114     }
1115 
1116     return appMgrServiceInner_->GetAppRunningStateByBundleName(bundleName);
1117 }
1118 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1119 int32_t AppMgrService::NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1120 {
1121     if (!IsReady()) {
1122         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1123         return ERR_INVALID_OPERATION;
1124     }
1125     return appMgrServiceInner_->NotifyLoadRepairPatch(bundleName, callback);
1126 }
1127 
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1128 int32_t AppMgrService::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1129 {
1130     if (!IsReady()) {
1131         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1132         return ERR_INVALID_OPERATION;
1133     }
1134     return appMgrServiceInner_->NotifyHotReloadPage(bundleName, callback);
1135 }
1136 
1137 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
SetContinuousTaskProcess(int32_t pid,bool isContinuousTask)1138 int32_t AppMgrService::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask)
1139 {
1140     if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(BS_PROCESS_NAME) &&
1141         !AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS)) {
1142         TAG_LOGE(AAFwkTag::ABILITYMGR, "not rss or foundation");
1143         return ERR_INVALID_OPERATION;
1144     }
1145     if (!IsReady()) {
1146         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1147         return ERR_INVALID_OPERATION;
1148     }
1149 
1150     return appMgrServiceInner_->SetContinuousTaskProcess(pid, isContinuousTask);
1151 }
1152 #endif
1153 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1154 int32_t AppMgrService::NotifyUnLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1155 {
1156     if (!IsReady()) {
1157         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1158         return ERR_INVALID_OPERATION;
1159     }
1160     return appMgrServiceInner_->NotifyUnLoadRepairPatch(bundleName, callback);
1161 }
1162 
JudgeAppSelfCalled(int32_t recordId)1163 bool AppMgrService::JudgeAppSelfCalled(int32_t recordId)
1164 {
1165     if (appMgrServiceInner_ == nullptr) {
1166         return false;
1167     }
1168 
1169     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
1170     std::shared_ptr<AppRunningRecord> appRecord = appMgrServiceInner_->GetAppRunningRecordByAppRecordId(recordId);
1171     if (appRecord == nullptr || ((appRecord->GetApplicationInfo())->accessTokenId) != callingTokenId) {
1172         TAG_LOGE(AAFwkTag::APPMGR, "not enabled");
1173         return false;
1174     }
1175 
1176     return true;
1177 }
1178 
IsSharedBundleRunning(const std::string & bundleName,uint32_t versionCode)1179 bool AppMgrService::IsSharedBundleRunning(const std::string &bundleName, uint32_t versionCode)
1180 {
1181     if (!IsReady()) {
1182         return false;
1183     }
1184     return appMgrServiceInner_->IsSharedBundleRunning(bundleName, versionCode);
1185 }
1186 
StartNativeProcessForDebugger(const AAFwk::Want & want)1187 int32_t AppMgrService::StartNativeProcessForDebugger(const AAFwk::Want &want)
1188 {
1189     if (!IsReady()) {
1190         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1191         return ERR_INVALID_OPERATION;
1192     }
1193     bool isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
1194     bool isLocalDebugCall = AAFwk::PermissionVerification::GetInstance()->VerifyStartLocalDebug();
1195     if (!isShellCall && !isLocalDebugCall) {
1196         TAG_LOGE(AAFwkTag::APPMGR, "permission denied");
1197         return ERR_INVALID_OPERATION;
1198     }
1199     auto ret = appMgrServiceInner_->StartNativeProcessForDebugger(want);
1200     if (ret != ERR_OK) {
1201         TAG_LOGE(AAFwkTag::APPMGR, "start native process fail");
1202     }
1203     return ret;
1204 }
1205 
GetBundleNameByPid(const int32_t pid,std::string & bundleName,int32_t & uid)1206 int32_t AppMgrService::GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid)
1207 {
1208     if (!IsReady()) {
1209         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1210         return ERR_INVALID_OPERATION;
1211     }
1212     return appMgrServiceInner_->GetBundleNameByPid(pid, bundleName, uid);
1213 }
1214 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info)1215 int32_t AppMgrService::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info)
1216 {
1217     if (!IsReady()) {
1218         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1219         return ERR_INVALID_OPERATION;
1220     }
1221     return appMgrServiceInner_->GetRunningProcessInfoByPid(pid, info);
1222 }
1223 
GetRunningProcessInfoByChildProcessPid(const pid_t childPid,OHOS::AppExecFwk::RunningProcessInfo & info)1224 int32_t AppMgrService::GetRunningProcessInfoByChildProcessPid(const pid_t childPid,
1225     OHOS::AppExecFwk::RunningProcessInfo &info)
1226 {
1227     if (!IsReady()) {
1228         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1229         return ERR_INVALID_OPERATION;
1230     }
1231     return appMgrServiceInner_->GetRunningProcessInfoByChildProcessPid(childPid, info);
1232 }
1233 
NotifyAppFault(const FaultData & faultData)1234 int32_t AppMgrService::NotifyAppFault(const FaultData &faultData)
1235 {
1236     if (!IsReady()) {
1237         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1238         return ERR_INVALID_OPERATION;
1239     }
1240 
1241     auto ret = appMgrServiceInner_->NotifyAppFault(faultData);
1242     if (ret != ERR_OK) {
1243         TAG_LOGE(AAFwkTag::APPMGR, "faultData fail");
1244     }
1245     return ret;
1246 }
1247 
NotifyAppFaultBySA(const AppFaultDataBySA & faultData)1248 int32_t AppMgrService::NotifyAppFaultBySA(const AppFaultDataBySA &faultData)
1249 {
1250     if (!IsReady()) {
1251         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1252         return ERR_INVALID_OPERATION;
1253     }
1254 
1255     auto ret = appMgrServiceInner_->NotifyAppFaultBySA(faultData);
1256     if (ret != ERR_OK) {
1257         TAG_LOGE(AAFwkTag::APPMGR, "faultData fail");
1258     }
1259     return ret;
1260 }
1261 
SetAppFreezeFilter(int32_t pid)1262 bool AppMgrService::SetAppFreezeFilter(int32_t pid)
1263 {
1264     if (!IsReady()) {
1265         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1266         return false;
1267     }
1268 
1269     auto ret = appMgrServiceInner_->SetAppFreezeFilter(pid);
1270     if (!ret) {
1271         TAG_LOGE(AAFwkTag::APPMGR, "SetAppFreezeFilter fail");
1272     }
1273     return ret;
1274 }
1275 
GetProcessMemoryByPid(const int32_t pid,int32_t & memorySize)1276 int32_t AppMgrService::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize)
1277 {
1278     if (!IsReady()) {
1279         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1280         return ERR_INVALID_OPERATION;
1281     }
1282 
1283     return appMgrServiceInner_->GetProcessMemoryByPid(pid, memorySize);
1284 }
1285 
GetRunningProcessInformation(const std::string & bundleName,int32_t userId,std::vector<RunningProcessInfo> & info)1286 int32_t AppMgrService::GetRunningProcessInformation(const std::string &bundleName, int32_t userId,
1287     std::vector<RunningProcessInfo> &info)
1288 {
1289     if (!IsReady()) {
1290         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1291         return ERR_INVALID_OPERATION;
1292     }
1293 
1294     return appMgrServiceInner_->GetRunningProcessInformation(bundleName, userId, info);
1295 }
1296 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1297 void AppMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
1298 {
1299     TAG_LOGI(AAFwkTag::APPMGR, "systemAbilityId: %{public}d add", systemAbilityId);
1300     if (!IsReady()) {
1301         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1302         return;
1303     }
1304 
1305     if (systemAbilityId != WINDOW_MANAGER_SERVICE_ID) {
1306         return;
1307     }
1308 
1309     appMgrServiceInner_->InitFocusListener();
1310 #ifdef SUPPORT_SCREEN
1311     appMgrServiceInner_->InitWindowVisibilityChangedListener();
1312     appMgrServiceInner_->InitWindowPidVisibilityChangedListener();
1313 #endif
1314 }
1315 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1316 void AppMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
1317 {
1318     TAG_LOGI(AAFwkTag::APPMGR, "systemAbilityId: %{public}d remove", systemAbilityId);
1319     if (!IsReady()) {
1320         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1321         return;
1322     }
1323 
1324     if (systemAbilityId != WINDOW_MANAGER_SERVICE_ID) {
1325         return;
1326     }
1327 
1328     appMgrServiceInner_->FreeFocusListener();
1329 #ifdef SUPPORT_SCREEN
1330     appMgrServiceInner_->FreeWindowVisibilityChangedListener();
1331     appMgrServiceInner_->FreeWindowPidVisibilityChangedListener();
1332 #endif
1333 }
1334 
ChangeAppGcState(pid_t pid,int32_t state)1335 int32_t AppMgrService::ChangeAppGcState(pid_t pid, int32_t state)
1336 {
1337     TAG_LOGD(AAFwkTag::APPMGR, "called");
1338     if (!appMgrServiceInner_) {
1339         return ERR_INVALID_VALUE;
1340     }
1341     return appMgrServiceInner_->ChangeAppGcState(pid, state);
1342 }
1343 
NotifyPageShow(const sptr<IRemoteObject> & token,const PageStateData & pageStateData)1344 int32_t AppMgrService::NotifyPageShow(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
1345 {
1346     TAG_LOGD(AAFwkTag::APPMGR,
1347         "bundleName: %{public}s, moduelName: %{public}s, abilityName: %{public}s, pageName: %{public}s",
1348         pageStateData.bundleName.c_str(), pageStateData.moduleName.c_str(), pageStateData.abilityName.c_str(),
1349         pageStateData.pageName.c_str());
1350     if (!IsReady()) {
1351         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1352         return ERR_INVALID_OPERATION;
1353     }
1354     return appMgrServiceInner_->NotifyPageShow(token, pageStateData);
1355 }
1356 
NotifyPageHide(const sptr<IRemoteObject> & token,const PageStateData & pageStateData)1357 int32_t AppMgrService::NotifyPageHide(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
1358 {
1359     TAG_LOGD(AAFwkTag::APPMGR,
1360         "bundleName: %{public}s, moduelName: %{public}s, abilityName: %{public}s, pageName: %{public}s",
1361         pageStateData.bundleName.c_str(), pageStateData.moduleName.c_str(), pageStateData.abilityName.c_str(),
1362         pageStateData.pageName.c_str());
1363     if (!IsReady()) {
1364         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1365         return ERR_INVALID_OPERATION;
1366     }
1367     return appMgrServiceInner_->NotifyPageHide(token, pageStateData);
1368 }
1369 
RegisterAppRunningStatusListener(const sptr<IRemoteObject> & listener)1370 int32_t AppMgrService::RegisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
1371 {
1372     TAG_LOGD(AAFwkTag::APPMGR, "called");
1373     if (!IsReady()) {
1374         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1375         return ERR_INVALID_OPERATION;
1376     }
1377     return appMgrServiceInner_->RegisterAppRunningStatusListener(listener);
1378 }
1379 
UnregisterAppRunningStatusListener(const sptr<IRemoteObject> & listener)1380 int32_t AppMgrService::UnregisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
1381 {
1382     TAG_LOGD(AAFwkTag::APPMGR, "called");
1383     if (!IsReady()) {
1384         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1385         return ERR_INVALID_OPERATION;
1386     }
1387     return appMgrServiceInner_->UnregisterAppRunningStatusListener(listener);
1388 }
1389 
RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)1390 int32_t AppMgrService::RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
1391 {
1392     TAG_LOGD(AAFwkTag::APPMGR, "called");
1393     if (!IsReady()) {
1394         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1395         return ERR_INVALID_OPERATION;
1396     }
1397     return appMgrServiceInner_->RegisterAppForegroundStateObserver(observer);
1398 }
1399 
UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)1400 int32_t AppMgrService::UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
1401 {
1402     TAG_LOGD(AAFwkTag::APPMGR, "called");
1403     if (!IsReady()) {
1404         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1405         return ERR_INVALID_OPERATION;
1406     }
1407     return appMgrServiceInner_->UnregisterAppForegroundStateObserver(observer);
1408 }
1409 
IsApplicationRunning(const std::string & bundleName,bool & isRunning)1410 int32_t AppMgrService::IsApplicationRunning(const std::string &bundleName, bool &isRunning)
1411 {
1412     if (!IsReady()) {
1413         return ERR_INVALID_OPERATION;
1414     }
1415     return appMgrServiceInner_->IsApplicationRunning(bundleName, isRunning);
1416 }
1417 
IsAppRunning(const std::string & bundleName,int32_t appCloneIndex,bool & isRunning)1418 int32_t AppMgrService::IsAppRunning(const std::string &bundleName, int32_t appCloneIndex, bool &isRunning)
1419 {
1420     isRunning = false;
1421     if (!IsReady()) {
1422         return ERR_INVALID_OPERATION;
1423     }
1424     return appMgrServiceInner_->IsAppRunning(bundleName, appCloneIndex, isRunning);
1425 }
1426 
IsAppRunningByBundleNameAndUserId(const std::string & bundleName,int32_t userId,bool & isRunning)1427 int32_t AppMgrService::IsAppRunningByBundleNameAndUserId(const std::string &bundleName, int32_t userId,
1428     bool &isRunning)
1429 {
1430     isRunning = false;
1431     if (!IsReady()) {
1432         return ERR_INVALID_OPERATION;
1433     }
1434     return appMgrServiceInner_->IsAppRunningByBundleNameAndUserId(bundleName, userId, isRunning);
1435 }
1436 
1437 #ifdef SUPPORT_CHILD_PROCESS
StartChildProcess(pid_t & childPid,const ChildProcessRequest & request)1438 int32_t AppMgrService::StartChildProcess(pid_t &childPid, const ChildProcessRequest &request)
1439 {
1440     TAG_LOGD(AAFwkTag::APPMGR, "called");
1441     std::vector<FdGuard> fds;
1442     for (const auto &[name, fd] : request.args.fds) {
1443         fds.emplace_back(fd);
1444     }
1445     if (!IsReady()) {
1446         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1447         return ERR_INVALID_OPERATION;
1448     }
1449 
1450     return appMgrServiceInner_->StartChildProcess(IPCSkeleton::GetCallingPid(), childPid, request);
1451 }
1452 
GetChildProcessInfoForSelf(ChildProcessInfo & info)1453 int32_t AppMgrService::GetChildProcessInfoForSelf(ChildProcessInfo &info)
1454 {
1455     if (!IsReady()) {
1456         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1457         return ERR_INVALID_OPERATION;
1458     }
1459     return appMgrServiceInner_->GetChildProcessInfoForSelf(info);
1460 }
1461 
AttachChildProcess(const sptr<IRemoteObject> & childScheduler)1462 void AppMgrService::AttachChildProcess(const sptr<IRemoteObject> &childScheduler)
1463 {
1464     TAG_LOGD(AAFwkTag::APPMGR, "AttachChildProcess.");
1465     if (!IsReady()) {
1466         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1467         return;
1468     }
1469     if (!taskHandler_) {
1470         TAG_LOGE(AAFwkTag::APPMGR, "null taskHandler_");
1471         return;
1472     }
1473     pid_t pid = IPCSkeleton::GetCallingPid();
1474     std::function<void()> task = [appMgrServiceInner = appMgrServiceInner_, pid, childScheduler]() {
1475         appMgrServiceInner->AttachChildProcess(pid, iface_cast<IChildScheduler>(childScheduler));
1476     };
1477     taskHandler_->SubmitTask(task, AAFwk::TaskAttribute{
1478         .taskName_ = TASK_ATTACH_CHILD_PROCESS,
1479         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
1480     });
1481 }
1482 
ExitChildProcessSafely()1483 void AppMgrService::ExitChildProcessSafely()
1484 {
1485     if (!IsReady()) {
1486         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1487         return;
1488     }
1489     if (!taskHandler_) {
1490         TAG_LOGE(AAFwkTag::APPMGR, "null taskHandler_");
1491         return;
1492     }
1493     pid_t pid = IPCSkeleton::GetCallingPid();
1494     std::function<void()> task = [appMgrServiceInner = appMgrServiceInner_, pid]() {
1495         appMgrServiceInner->ExitChildProcessSafelyByChildPid(pid);
1496     };
1497     taskHandler_->SubmitTask(task, AAFwk::TaskAttribute{
1498         .taskName_ = TASK_EXIT_CHILD_PROCESS_SAFELY,
1499         .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
1500     });
1501 }
1502 #endif // SUPPORT_CHILD_PROCESS
1503 
IsFinalAppProcess()1504 bool AppMgrService::IsFinalAppProcess()
1505 {
1506     if (!IsReady()) {
1507         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1508         return false;
1509     }
1510     return appMgrServiceInner_->IsFinalAppProcessByBundleName("");
1511 }
1512 
RegisterRenderStateObserver(const sptr<IRenderStateObserver> & observer)1513 int32_t AppMgrService::RegisterRenderStateObserver(const sptr<IRenderStateObserver> &observer)
1514 {
1515     if (!IsReady()) {
1516         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1517         return ERR_INVALID_OPERATION;
1518     }
1519 
1520     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
1521         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
1522         return ERR_PERMISSION_DENIED;
1523     }
1524     return appMgrServiceInner_->RegisterRenderStateObserver(observer);
1525 }
1526 
UnregisterRenderStateObserver(const sptr<IRenderStateObserver> & observer)1527 int32_t AppMgrService::UnregisterRenderStateObserver(const sptr<IRenderStateObserver> &observer)
1528 {
1529     if (!IsReady()) {
1530         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1531         return ERR_INVALID_OPERATION;
1532     }
1533 
1534     if (AAFwk::PermissionVerification::GetInstance()->VerifyAppStateObserverPermission() == ERR_PERMISSION_DENIED) {
1535         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
1536         return ERR_PERMISSION_DENIED;
1537     }
1538     return appMgrServiceInner_->UnregisterRenderStateObserver(observer);
1539 }
1540 
UpdateRenderState(pid_t renderPid,int32_t state)1541 int32_t AppMgrService::UpdateRenderState(pid_t renderPid, int32_t state)
1542 {
1543     if (!IsReady()) {
1544         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1545         return ERR_INVALID_OPERATION;
1546     }
1547     return appMgrServiceInner_->UpdateRenderState(renderPid, state);
1548 }
1549 
SignRestartAppFlag(int32_t uid,const std::string & instanceKey)1550 int32_t AppMgrService::SignRestartAppFlag(int32_t uid, const std::string &instanceKey)
1551 {
1552     if (!IsReady()) {
1553         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1554         return ERR_INVALID_OPERATION;
1555     }
1556     bool isCallingPermission =
1557         AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS);
1558     if (!isCallingPermission) {
1559         TAG_LOGE(AAFwkTag::APPMGR, "verification failed");
1560         return ERR_PERMISSION_DENIED;
1561     }
1562     return appMgrServiceInner_->SignRestartAppFlag(uid, instanceKey);
1563 }
1564 
GetAppRunningUniqueIdByPid(pid_t pid,std::string & appRunningUniqueId)1565 int32_t AppMgrService::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId)
1566 {
1567     if (!IsReady()) {
1568         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1569         return ERR_INVALID_OPERATION;
1570     }
1571     bool isCallingPermission = AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
1572         AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1573     if (!isCallingPermission) {
1574         TAG_LOGE(AAFwkTag::APPMGR, "GetAppRunningUniqueIdByPid not SA call or verification failed");
1575         return ERR_PERMISSION_DENIED;
1576     }
1577     return appMgrServiceInner_->GetAppRunningUniqueIdByPid(pid, appRunningUniqueId);
1578 }
1579 
GetAllUIExtensionRootHostPid(pid_t pid,std::vector<pid_t> & hostPids)1580 int32_t AppMgrService::GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids)
1581 {
1582     if (!IsReady()) {
1583         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1584         return ERR_INVALID_OPERATION;
1585     }
1586 
1587     return appMgrServiceInner_->GetAllUIExtensionRootHostPid(pid, hostPids);
1588 }
1589 
GetAllUIExtensionProviderPid(pid_t hostPid,std::vector<pid_t> & providerPids)1590 int32_t AppMgrService::GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids)
1591 {
1592     if (!IsReady()) {
1593         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1594         return ERR_INVALID_OPERATION;
1595     }
1596 
1597     return appMgrServiceInner_->GetAllUIExtensionProviderPid(hostPid, providerPids);
1598 }
1599 
NotifyMemorySizeStateChanged(bool isMemorySizeSufficient)1600 int32_t AppMgrService::NotifyMemorySizeStateChanged(bool isMemorySizeSufficient)
1601 {
1602     if (!IsReady()) {
1603         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1604         return ERR_INVALID_OPERATION;
1605     }
1606 
1607     return appMgrServiceInner_->NotifyMemorySizeStateChanged(isMemorySizeSufficient);
1608 }
1609 
SetSupportedProcessCacheSelf(bool isSupport)1610 int32_t AppMgrService::SetSupportedProcessCacheSelf(bool isSupport)
1611 {
1612     TAG_LOGI(AAFwkTag::APPMGR, "call");
1613     if (!IsReady()) {
1614         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1615         return ERR_INVALID_OPERATION;
1616     }
1617     return appMgrServiceInner_->SetSupportedProcessCacheSelf(isSupport);
1618 }
1619 
SetSupportedProcessCache(int32_t pid,bool isSupport)1620 int32_t AppMgrService::SetSupportedProcessCache(int32_t pid, bool isSupport)
1621 {
1622     TAG_LOGI(AAFwkTag::APPMGR, "Called");
1623     if (!IsReady()) {
1624         TAG_LOGE(AAFwkTag::APPMGR, "Not ready.");
1625         return ERR_INVALID_OPERATION;
1626     }
1627     if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS)) {
1628         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not foundation");
1629         return ERR_INVALID_OPERATION;
1630     }
1631     return appMgrServiceInner_->SetSupportedProcessCache(pid, isSupport);
1632 }
1633 
SetAppAssertionPauseState(bool flag)1634 void AppMgrService::SetAppAssertionPauseState(bool flag)
1635 {
1636     TAG_LOGI(AAFwkTag::APPMGR, "call");
1637     if (!IsReady()) {
1638         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1639         return;
1640     }
1641     return appMgrServiceInner_->SetAppAssertionPauseState(flag);
1642 }
1643 
1644 #ifdef SUPPORT_CHILD_PROCESS
StartNativeChildProcess(const std::string & libName,int32_t childProcessCount,const sptr<IRemoteObject> & callback)1645 int32_t AppMgrService::StartNativeChildProcess(const std::string &libName, int32_t childProcessCount,
1646     const sptr<IRemoteObject> &callback)
1647 {
1648     TAG_LOGI(AAFwkTag::APPMGR, "call");
1649     if (!IsReady()) {
1650         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1651         return ERR_INVALID_OPERATION;
1652     }
1653 
1654     return appMgrServiceInner_->StartNativeChildProcess(
1655         IPCSkeleton::GetCallingPid(), libName, childProcessCount, callback);
1656 }
1657 #endif // SUPPORT_CHILD_PROCESS
1658 
CheckCallingIsUserTestMode(const pid_t pid,bool & isUserTest)1659 int32_t AppMgrService::CheckCallingIsUserTestMode(const pid_t pid, bool &isUserTest)
1660 {
1661     TAG_LOGD(AAFwkTag::APPMGR, "called");
1662     if (!appMgrServiceInner_) {
1663         return ERR_INVALID_VALUE;
1664     }
1665     return appMgrServiceInner_->CheckCallingIsUserTestModeInner(pid, isUserTest);
1666 }
1667 
NotifyProcessDependedOnWeb()1668 int32_t AppMgrService::NotifyProcessDependedOnWeb()
1669 {
1670     TAG_LOGD(AAFwkTag::APPMGR, "called");
1671     if (!appMgrServiceInner_) {
1672         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1673         return ERR_INVALID_VALUE;
1674     }
1675     return appMgrServiceInner_->NotifyProcessDependedOnWeb();
1676 }
1677 
KillProcessDependedOnWeb()1678 void AppMgrService::KillProcessDependedOnWeb()
1679 {
1680     TAG_LOGD(AAFwkTag::APPMGR, "called");
1681     if (!AAFwk::PermissionVerification::GetInstance()->VerifyKillProcessDependedOnWebPermission()) {
1682         TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission");
1683         return;
1684     }
1685     if (!appMgrServiceInner_) {
1686         return;
1687     }
1688     appMgrServiceInner_->KillProcessDependedOnWeb();
1689 }
1690 
RestartResidentProcessDependedOnWeb()1691 void AppMgrService::RestartResidentProcessDependedOnWeb()
1692 {
1693     TAG_LOGD(AAFwkTag::APPMGR, "called");
1694     if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS)) {
1695         TAG_LOGE(AAFwkTag::ABILITYMGR, "not foundation");
1696         return;
1697     }
1698     if (!appMgrServiceInner_) {
1699         return;
1700     }
1701     appMgrServiceInner_->RestartResidentProcessDependedOnWeb();
1702 }
1703 
GetSupportedProcessCachePids(const std::string & bundleName,std::vector<int32_t> & pidList)1704 int32_t AppMgrService::GetSupportedProcessCachePids(const std::string &bundleName,
1705     std::vector<int32_t> &pidList)
1706 {
1707     if (!IsReady()) {
1708         TAG_LOGE(AAFwkTag::APPMGR, "not ready");
1709         return ERR_INVALID_OPERATION;
1710     }
1711     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
1712         TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA");
1713         return AAFwk::ERR_NOT_SYSTEM_APP;
1714     }
1715     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1716     if (!isPerm) {
1717         return AAFwk::CHECK_PERMISSION_FAILED;
1718     }
1719     if (!DelayedSingleton<CacheProcessManager>::GetInstance()->QueryEnableProcessCache()) {
1720         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
1721     }
1722     return appMgrServiceInner_->GetSupportedProcessCachePids(bundleName, pidList);
1723 }
1724 
RegisterKiaInterceptor(const sptr<IKiaInterceptor> & interceptor)1725 int32_t AppMgrService::RegisterKiaInterceptor(const sptr<IKiaInterceptor> &interceptor)
1726 {
1727     TAG_LOGD(AAFwkTag::APPMGR, "Called");
1728     if (!appMgrServiceInner_) {
1729         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1730         return ERR_INVALID_VALUE;
1731     }
1732     return appMgrServiceInner_->RegisterKiaInterceptor(interceptor);
1733 }
1734 
CheckIsKiaProcess(pid_t pid,bool & isKia)1735 int32_t AppMgrService::CheckIsKiaProcess(pid_t pid, bool &isKia)
1736 {
1737     TAG_LOGD(AAFwkTag::APPMGR, "Called");
1738     if (!appMgrServiceInner_) {
1739         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1740         return ERR_INVALID_VALUE;
1741     }
1742     return appMgrServiceInner_->CheckIsKiaProcess(pid, isKia);
1743 }
1744 
KillAppSelfWithInstanceKey(const std::string & instanceKey,bool clearPageStack,const std::string & reason)1745 int32_t AppMgrService::KillAppSelfWithInstanceKey(const std::string &instanceKey, bool clearPageStack,
1746     const std::string& reason)
1747 {
1748     if (!appMgrServiceInner_) {
1749         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1750         return ERR_INVALID_VALUE;
1751     }
1752     return appMgrServiceInner_->KillAppSelfWithInstanceKey(instanceKey, clearPageStack, reason);
1753 }
1754 
UpdateInstanceKeyBySpecifiedId(int32_t specifiedId,std::string & instanceKey)1755 void AppMgrService::UpdateInstanceKeyBySpecifiedId(int32_t specifiedId, std::string &instanceKey)
1756 {
1757     if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS)) {
1758         TAG_LOGE(AAFwkTag::APPMGR, "not foundation");
1759         return;
1760     }
1761     if (!appMgrServiceInner_) {
1762         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1763         return;
1764     }
1765     appMgrServiceInner_->UpdateInstanceKeyBySpecifiedId(specifiedId, instanceKey);
1766 }
1767 
IsSpecifiedModuleLoaded(const AAFwk::Want & want,const AbilityInfo & abilityInfo,bool & result)1768 int32_t AppMgrService::IsSpecifiedModuleLoaded(const AAFwk::Want &want, const AbilityInfo &abilityInfo, bool &result)
1769 {
1770     if (!IsReady()) {
1771         return ERR_INVALID_OPERATION;
1772     }
1773     pid_t callingPid = IPCSkeleton::GetCallingPid();
1774     pid_t pid = getprocpid();
1775     if (callingPid != pid) {
1776         TAG_LOGE(AAFwkTag::APPMGR, "other process");
1777         return ERR_INVALID_OPERATION;
1778     }
1779     if (!appMgrServiceInner_) {
1780         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1781         return ERR_INVALID_VALUE;
1782     }
1783     result = appMgrServiceInner_->IsSpecifiedModuleLoaded(want, abilityInfo);
1784     return ERR_OK;
1785 }
1786 
UpdateProcessMemoryState(const std::vector<ProcessMemoryState> & procMemState)1787 int32_t AppMgrService::UpdateProcessMemoryState(const std::vector<ProcessMemoryState> &procMemState)
1788 {
1789     TAG_LOGI(AAFwkTag::APPMGR, "procMemState.size = %{public}zu", procMemState.size());
1790     if (!IsReady()) {
1791         return ERR_INVALID_OPERATION;
1792     }
1793     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
1794         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
1795         TAG_LOGE(AAFwkTag::APPMGR, "caller is not sa or shell");
1796         return ERR_PERMISSION_DENIED;
1797     }
1798     if (!AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
1799         HIVIEW_PROCESS_NAME)) {
1800         TAG_LOGW(AAFwkTag::APPMGR, "caller not sa dfx");
1801     }
1802     if (!appMgrServiceInner_) {
1803         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1804         return ERR_INVALID_VALUE;
1805     }
1806     return appMgrServiceInner_->UpdateProcessMemoryState(procMemState);
1807 }
1808 
GetKilledProcessInfo(int pid,int uid,KilledProcessInfo & info)1809 int32_t AppMgrService::GetKilledProcessInfo(int pid, int uid, KilledProcessInfo &info)
1810 {
1811     if (!IsReady()) {
1812         return AAFwk::ERR_APP_MGR_SERVICE_NOT_READY;
1813     }
1814     pid_t callingPid = IPCSkeleton::GetCallingPid();
1815     pid_t currentPid = getprocpid();
1816     if (callingPid != currentPid) {
1817         TAG_LOGE(AAFwkTag::APPMGR, "other process");
1818         return AAFwk::ERR_NO_ALLOW_OUTSIDE_CALL;
1819     }
1820     if (!appMgrServiceInner_) {
1821         TAG_LOGE(AAFwkTag::APPMGR, "appMgrServiceInner_ is nullptr");
1822         return AAFwk::ERR_NULL_APP_MGR_SERVICE_INNER;
1823     }
1824     return appMgrServiceInner_->GetKilledProcessInfo(pid, uid, info);
1825 }
1826 }  // namespace AppExecFwk
1827 }  // namespace OHOS
1828