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