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