1 /*
2 * Copyright (c) 2021-2022 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 <nlohmann/json.hpp>
19 #include <sys/types.h>
20
21 #include "datetime_ex.h"
22 #include "ipc_skeleton.h"
23 #include "system_ability_definition.h"
24
25 #include "app_death_recipient.h"
26 #include "app_mgr_constants.h"
27 #include "hilog_wrapper.h"
28 #include "perf_profile.h"
29 #include "xcollie/watchdog.h"
30
31 #include "permission_constants.h"
32 #include "permission_verification.h"
33 #include "system_environment_information.h"
34
35 namespace OHOS {
36 namespace AppExecFwk {
37 namespace {
38 static const int EXPERIENCE_MEM_THRESHOLD = 20;
39 static const int APP_MS_TIMEOUT = 60;
40 static const float PERCENTAGE = 100.0;
41 const std::string TASK_ATTACH_APPLICATION = "AttachApplicationTask";
42 const std::string TASK_APPLICATION_FOREGROUNDED = "ApplicationForegroundedTask";
43 const std::string TASK_APPLICATION_BACKGROUNDED = "ApplicationBackgroundedTask";
44 const std::string TASK_APPLICATION_TERMINATED = "ApplicationTerminatedTask";
45 const std::string TASK_ABILITY_CLEANED = "AbilityCleanedTask";
46 const std::string TASK_ADD_APP_DEATH_RECIPIENT = "AddAppRecipientTask";
47 const std::string TASK_CLEAR_UP_APPLICATION_DATA = "ClearUpApplicationDataTask";
48 const std::string TASK_STARTUP_RESIDENT_PROCESS = "StartupResidentProcess";
49 const std::string TASK_ADD_ABILITY_STAGE_DONE = "AddAbilityStageDone";
50 const std::string TASK_START_USER_TEST_PROCESS = "StartUserTestProcess";
51 const std::string TASK_FINISH_USER_TEST = "FinishUserTest";
52 const std::string TASK_ATTACH_RENDER_PROCESS = "AttachRenderTask";
53 } // namespace
54
55 REGISTER_SYSTEM_ABILITY_BY_ID(AppMgrService, APP_MGR_SERVICE_ID, true);
56
AppMgrService()57 AppMgrService::AppMgrService()
58 {
59 appMgrServiceInner_ = std::make_shared<AppMgrServiceInner>();
60 HILOG_INFO("instance created with no para");
61 PerfProfile::GetInstance().SetAmsLoadStartTime(GetTickCount());
62 }
63
AppMgrService(const int32_t serviceId,bool runOnCreate)64 AppMgrService::AppMgrService(const int32_t serviceId, bool runOnCreate) : SystemAbility(serviceId, runOnCreate)
65 {
66 appMgrServiceInner_ = std::make_shared<AppMgrServiceInner>();
67 HILOG_INFO("instance created");
68 PerfProfile::GetInstance().SetAmsLoadStartTime(GetTickCount());
69 }
70
~AppMgrService()71 AppMgrService::~AppMgrService()
72 {
73 HILOG_INFO("instance destroyed");
74 }
75
OnStart()76 void AppMgrService::OnStart()
77 {
78 HILOG_INFO("ready to start service");
79 if (appMgrServiceState_.serviceRunningState == ServiceRunningState::STATE_RUNNING) {
80 HILOG_WARN("failed to start service since it's already running");
81 return;
82 }
83
84 ErrCode errCode = Init();
85 if (FAILED(errCode)) {
86 HILOG_ERROR("init failed, errCode: %{public}08x", errCode);
87 return;
88 }
89 appMgrServiceState_.serviceRunningState = ServiceRunningState::STATE_RUNNING;
90 HILOG_INFO("start service success");
91 PerfProfile::GetInstance().SetAmsLoadEndTime(GetTickCount());
92 PerfProfile::GetInstance().Dump();
93 }
94
OnStop()95 void AppMgrService::OnStop()
96 {
97 HILOG_INFO("ready to stop service");
98 appMgrServiceState_.serviceRunningState = ServiceRunningState::STATE_NOT_START;
99 handler_.reset();
100 runner_.reset();
101 if (appMgrServiceInner_) {
102 appMgrServiceInner_->OnStop();
103 }
104 HILOG_INFO("stop service success");
105 }
106
SetInnerService(const std::shared_ptr<AppMgrServiceInner> & innerService)107 void AppMgrService::SetInnerService(const std::shared_ptr<AppMgrServiceInner> &innerService)
108 {
109 appMgrServiceInner_ = innerService;
110 }
111
QueryServiceState()112 AppMgrServiceState AppMgrService::QueryServiceState()
113 {
114 if (appMgrServiceInner_) {
115 appMgrServiceState_.connectionState = appMgrServiceInner_->QueryAppSpawnConnectionState();
116 }
117 return appMgrServiceState_;
118 }
119
Init()120 ErrCode AppMgrService::Init()
121 {
122 HILOG_INFO("ready to init");
123 // start main thread message loop.
124 runner_ = EventRunner::Create(Constants::APP_MGR_SERVICE_NAME);
125 if (!runner_) {
126 HILOG_ERROR("init failed due to create runner error");
127 return ERR_INVALID_OPERATION;
128 }
129 if (!appMgrServiceInner_) {
130 HILOG_ERROR("init failed without inner service");
131 return ERR_INVALID_OPERATION;
132 }
133 appMgrServiceInner_->Init();
134 handler_ = std::make_shared<AMSEventHandler>(runner_, appMgrServiceInner_);
135
136 appMgrServiceInner_->SetEventHandler(handler_);
137 ErrCode openErr = appMgrServiceInner_->OpenAppSpawnConnection();
138 if (FAILED(openErr)) {
139 HILOG_WARN("failed to connect to AppSpawnDaemon! errCode: %{public}08x", openErr);
140 }
141 if (!Publish(this)) {
142 HILOG_ERROR("failed to publish appmgrservice to systemAbilityMgr");
143 return ERR_APPEXECFWK_SERVICE_NOT_CONNECTED;
144 }
145 amsMgrScheduler_ = new (std::nothrow) AmsMgrScheduler(appMgrServiceInner_, handler_);
146 if (!amsMgrScheduler_) {
147 HILOG_ERROR("init failed without ams scheduler");
148 return ERR_INVALID_OPERATION;
149 }
150 if (HiviewDFX::Watchdog::GetInstance().AddThread("APPMSWatchdog", handler_, APP_MS_TIMEOUT) != 0) {
151 HILOG_ERROR("HiviewDFX::Watchdog::GetInstance AddThread Fail");
152 }
153 HILOG_INFO("init success");
154 return ERR_OK;
155 }
156
CheckPermission(const int32_t recordId,const std::string & permission)157 int32_t AppMgrService::CheckPermission(
158 [[maybe_unused]] const int32_t recordId, [[maybe_unused]] const std::string &permission)
159 {
160 HILOG_INFO("check application's permission");
161
162 return ERR_OK;
163 }
164
AttachApplication(const sptr<IRemoteObject> & app)165 void AppMgrService::AttachApplication(const sptr<IRemoteObject> &app)
166 {
167 if (!IsReady()) {
168 HILOG_ERROR("AttachApplication failed, not ready.");
169 return;
170 }
171
172 pid_t pid = IPCSkeleton::GetCallingPid();
173 AddAppDeathRecipient(pid);
174 std::function<void()> attachApplicationFunc =
175 std::bind(&AppMgrServiceInner::AttachApplication, appMgrServiceInner_, pid, iface_cast<IAppScheduler>(app));
176 handler_->PostTask(attachApplicationFunc, TASK_ATTACH_APPLICATION);
177 }
178
ApplicationForegrounded(const int32_t recordId)179 void AppMgrService::ApplicationForegrounded(const int32_t recordId)
180 {
181 if (!IsReady()) {
182 return;
183 }
184 if (!JudgeSelfCalledByRecordId(recordId)) {
185 return;
186 }
187 std::function<void()> applicationForegroundedFunc =
188 std::bind(&AppMgrServiceInner::ApplicationForegrounded, appMgrServiceInner_, recordId);
189 handler_->PostTask(applicationForegroundedFunc, TASK_APPLICATION_FOREGROUNDED);
190 }
191
ApplicationBackgrounded(const int32_t recordId)192 void AppMgrService::ApplicationBackgrounded(const int32_t recordId)
193 {
194 if (!IsReady()) {
195 return;
196 }
197 if (!JudgeSelfCalledByRecordId(recordId)) {
198 return;
199 }
200 std::function<void()> applicationBackgroundedFunc =
201 std::bind(&AppMgrServiceInner::ApplicationBackgrounded, appMgrServiceInner_, recordId);
202 handler_->PostTask(applicationBackgroundedFunc, TASK_APPLICATION_BACKGROUNDED);
203 }
204
ApplicationTerminated(const int32_t recordId)205 void AppMgrService::ApplicationTerminated(const int32_t recordId)
206 {
207 if (!IsReady()) {
208 return;
209 }
210 if (!JudgeSelfCalledByRecordId(recordId)) {
211 return;
212 }
213 std::function<void()> applicationTerminatedFunc =
214 std::bind(&AppMgrServiceInner::ApplicationTerminated, appMgrServiceInner_, recordId);
215 handler_->PostTask(applicationTerminatedFunc, TASK_APPLICATION_TERMINATED);
216 }
217
AbilityCleaned(const sptr<IRemoteObject> & token)218 void AppMgrService::AbilityCleaned(const sptr<IRemoteObject> &token)
219 {
220 if (!IsReady()) {
221 return;
222 }
223 std::function<void()> abilityCleanedFunc =
224 std::bind(&AppMgrServiceInner::AbilityTerminated, appMgrServiceInner_, token);
225 handler_->PostTask(abilityCleanedFunc, TASK_ABILITY_CLEANED);
226 }
227
IsReady() const228 bool AppMgrService::IsReady() const
229 {
230 if (!appMgrServiceInner_) {
231 HILOG_ERROR("appMgrServiceInner is null");
232 return false;
233 }
234 if (!handler_) {
235 HILOG_ERROR("handler is null");
236 return false;
237 }
238 return true;
239 }
240
AddAppDeathRecipient(const pid_t pid) const241 void AppMgrService::AddAppDeathRecipient(const pid_t pid) const
242 {
243 if (!IsReady()) {
244 return;
245 }
246 sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
247 appDeathRecipient->SetEventHandler(handler_);
248 appDeathRecipient->SetAppMgrServiceInner(appMgrServiceInner_);
249 std::function<void()> addAppRecipientFunc =
250 std::bind(&AppMgrServiceInner::AddAppDeathRecipient, appMgrServiceInner_, pid, appDeathRecipient);
251 handler_->PostTask(addAppRecipientFunc, TASK_ADD_APP_DEATH_RECIPIENT);
252 }
253
StartupResidentProcess(const std::vector<AppExecFwk::BundleInfo> & bundleInfos)254 void AppMgrService::StartupResidentProcess(const std::vector<AppExecFwk::BundleInfo> &bundleInfos)
255 {
256 if (!IsReady()) {
257 return;
258 }
259 pid_t callingPid = IPCSkeleton::GetCallingPid();
260 pid_t pid = getpid();
261 if (callingPid != pid) {
262 HILOG_ERROR("Not this process call.");
263 return;
264 }
265 HILOG_INFO("Notify start resident process");
266 std::function <void()> startupResidentProcess =
267 std::bind(&AppMgrServiceInner::LoadResidentProcess, appMgrServiceInner_, bundleInfos);
268 handler_->PostTask(startupResidentProcess, TASK_STARTUP_RESIDENT_PROCESS);
269 }
270
GetAmsMgr()271 sptr<IAmsMgr> AppMgrService::GetAmsMgr()
272 {
273 return amsMgrScheduler_;
274 }
275
ClearUpApplicationData(const std::string & bundleName)276 int32_t AppMgrService::ClearUpApplicationData(const std::string &bundleName)
277 {
278 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
279 if (!isSaCall) {
280 auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
281 AAFwk::PermissionConstants::PERMISSION_CLEAN_APPLICATION_DATA);
282 if (!isCallingPerm) {
283 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
284 return ERR_PERMISSION_DENIED;
285 }
286 }
287
288 if (!IsReady()) {
289 return ERR_INVALID_OPERATION;
290 }
291 int32_t uid = IPCSkeleton::GetCallingUid();
292 pid_t pid = IPCSkeleton::GetCallingPid();
293 std::function<void()> clearUpApplicationDataFunc =
294 std::bind(&AppMgrServiceInner::ClearUpApplicationData, appMgrServiceInner_, bundleName, uid, pid);
295 handler_->PostTask(clearUpApplicationDataFunc, TASK_CLEAR_UP_APPLICATION_DATA);
296 return ERR_OK;
297 }
298
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)299 int32_t AppMgrService::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
300 {
301 if (!IsReady()) {
302 return ERR_INVALID_OPERATION;
303 }
304 return appMgrServiceInner_->GetAllRunningProcesses(info);
305 }
306
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)307 int32_t AppMgrService::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
308 {
309 if (!IsReady()) {
310 return ERR_INVALID_OPERATION;
311 }
312 return appMgrServiceInner_->GetProcessRunningInfosByUserId(info, userId);
313 }
314
315 /**
316 * Get system memory information.
317 * @param SystemMemoryAttr, memory information.
318 */
GetSystemMemoryAttr(SystemMemoryAttr & memoryInfo,std::string & strConfig)319 void AppMgrService::GetSystemMemoryAttr(SystemMemoryAttr &memoryInfo, std::string &strConfig)
320 {
321 SystemEnv::KernelSystemMemoryInfo systemMemInfo;
322 SystemEnv::GetMemInfo(systemMemInfo);
323 int memThreshold = 0;
324 nlohmann::json memJson = nlohmann::json::parse(strConfig, nullptr, false);
325 if (memJson.is_discarded()) {
326 memThreshold = EXPERIENCE_MEM_THRESHOLD;
327 HILOG_ERROR("%{public}s, discarded memThreshold = %{public}d", __func__, EXPERIENCE_MEM_THRESHOLD);
328 } else {
329 if (!memJson.contains("memoryThreshold")) {
330 memThreshold = EXPERIENCE_MEM_THRESHOLD;
331 HILOG_ERROR("%{public}s, memThreshold = %{public}d", __func__, EXPERIENCE_MEM_THRESHOLD);
332 } else {
333 memThreshold = memJson.at("memorythreshold").get<int>();
334 HILOG_INFO("memThreshold = %{public}d", memThreshold);
335 }
336 }
337
338 memoryInfo.availSysMem_ = systemMemInfo.GetMemFree();
339 memoryInfo.totalSysMem_ = systemMemInfo.GetMemTotal();
340 memoryInfo.threshold_ = static_cast<int64_t>(memoryInfo.totalSysMem_ * memThreshold / PERCENTAGE);
341 memoryInfo.isSysInlowMem_ = memoryInfo.availSysMem_ < memoryInfo.threshold_;
342 }
343
AddAbilityStageDone(const int32_t recordId)344 void AppMgrService::AddAbilityStageDone(const int32_t recordId)
345 {
346 if (!IsReady()) {
347 return;
348 }
349 if (!JudgeSelfCalledByRecordId(recordId)) {
350 return;
351 }
352 std::function <void()> addAbilityStageDone =
353 std::bind(&AppMgrServiceInner::AddAbilityStageDone, appMgrServiceInner_, recordId);
354 handler_->PostTask(addAbilityStageDone, TASK_ADD_ABILITY_STAGE_DONE);
355 }
356
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)357 int32_t AppMgrService::RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
358 {
359 HILOG_INFO("%{public}s begin", __func__);
360 if (!IsReady()) {
361 HILOG_ERROR("%{public}s begin, not ready", __func__);
362 return ERR_INVALID_OPERATION;
363 }
364 return appMgrServiceInner_->RegisterApplicationStateObserver(observer);
365 }
366
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)367 int32_t AppMgrService::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
368 {
369 HILOG_INFO("%{public}s begin", __func__);
370 if (!IsReady()) {
371 HILOG_ERROR("%{public}s begin, not ready", __func__);
372 return ERR_INVALID_OPERATION;
373 }
374 return appMgrServiceInner_->UnregisterApplicationStateObserver(observer);
375 }
376
GetForegroundApplications(std::vector<AppStateData> & list)377 int32_t AppMgrService::GetForegroundApplications(std::vector<AppStateData> &list)
378 {
379 HILOG_INFO("%{public}s begin", __func__);
380 if (!IsReady()) {
381 HILOG_ERROR("%{public}s begin, not ready", __func__);
382 return ERR_INVALID_OPERATION;
383 }
384 return appMgrServiceInner_->GetForegroundApplications(list);
385 }
386
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const AppExecFwk::BundleInfo & bundleInfo,int32_t userId)387 int AppMgrService::StartUserTestProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
388 const AppExecFwk::BundleInfo &bundleInfo, int32_t userId)
389 {
390 if (!IsReady()) {
391 return ERR_INVALID_OPERATION;
392 }
393 std::function<void()> startUserTestProcessFunc =
394 std::bind(&AppMgrServiceInner::StartUserTestProcess, appMgrServiceInner_, want, observer, bundleInfo, userId);
395 handler_->PostTask(startUserTestProcessFunc, TASK_START_USER_TEST_PROCESS);
396 return ERR_OK;
397 }
398
FinishUserTest(const std::string & msg,const int & resultCode,const std::string & bundleName)399 int AppMgrService::FinishUserTest(const std::string &msg, const int &resultCode, const std::string &bundleName)
400 {
401 if (!IsReady()) {
402 return ERR_INVALID_OPERATION;
403 }
404 pid_t callingPid = IPCSkeleton::GetCallingPid();
405 std::function<void()> finishUserTestProcessFunc =
406 std::bind(&AppMgrServiceInner::FinishUserTest, appMgrServiceInner_, msg, resultCode, bundleName, callingPid);
407 handler_->PostTask(finishUserTestProcessFunc, TASK_FINISH_USER_TEST);
408 return ERR_OK;
409 }
410
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)411 void AppMgrService::ScheduleAcceptWantDone(const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
412 {
413 if (!IsReady()) {
414 return;
415 }
416 if (!JudgeSelfCalledByRecordId(recordId)) {
417 return;
418 }
419 auto task = [=]() { appMgrServiceInner_->ScheduleAcceptWantDone(recordId, want, flag); };
420 handler_->PostTask(task);
421 }
422
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)423 int AppMgrService::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
424 {
425 if (!IsReady()) {
426 return ERR_INVALID_OPERATION;
427 }
428 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
429 if (!isSaCall) {
430 HILOG_ERROR("Not SA call.");
431 return ERR_INVALID_OPERATION;
432 }
433 return appMgrServiceInner_->GetAbilityRecordsByProcessID(pid, tokens);
434 }
435
StartRenderProcess(const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,pid_t & renderPid)436 int32_t AppMgrService::StartRenderProcess(const std::string &renderParam, int32_t ipcFd,
437 int32_t sharedFd, pid_t &renderPid)
438 {
439 if (!IsReady()) {
440 HILOG_ERROR("StartRenderProcess failed, AppMgrService not ready.");
441 return ERR_INVALID_OPERATION;
442 }
443
444 return appMgrServiceInner_->StartRenderProcess(IPCSkeleton::GetCallingPid(),
445 renderParam, ipcFd, sharedFd, renderPid);
446 }
447
AttachRenderProcess(const sptr<IRemoteObject> & scheduler)448 void AppMgrService::AttachRenderProcess(const sptr<IRemoteObject> &scheduler)
449 {
450 HILOG_DEBUG("AttachRenderProcess called.");
451 if (!IsReady()) {
452 HILOG_ERROR("AttachRenderProcess failed, not ready.");
453 return;
454 }
455
456 auto pid = IPCSkeleton::GetCallingPid();
457 auto fun = std::bind(&AppMgrServiceInner::AttachRenderProcess,
458 appMgrServiceInner_, pid, iface_cast<IRenderScheduler>(scheduler));
459 handler_->PostTask(fun, TASK_ATTACH_RENDER_PROCESS);
460 }
461
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)462 int32_t AppMgrService::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
463 {
464 if (!IsReady()) {
465 HILOG_ERROR("GetRenderProcessTerminationStatus failed, AppMgrService not ready.");
466 return ERR_INVALID_OPERATION;
467 }
468
469 return appMgrServiceInner_->GetRenderProcessTerminationStatus(renderPid, status);
470 }
471
PostANRTaskByProcessID(const pid_t pid)472 void AppMgrService::PostANRTaskByProcessID(const pid_t pid)
473 {
474 HILOG_DEBUG("PostANRTaskByProcessID called.");
475 if (!IsReady()) {
476 HILOG_ERROR("AttachRenderProcess failed, not ready.");
477 return;
478 }
479 auto appRecord = appMgrServiceInner_->GetAppRunningRecordByPid(pid);
480 if (!appRecord) {
481 HILOG_ERROR("no such appRecord");
482 return;
483 }
484 auto object = appRecord->GetApplicationClient();
485 if (!object) {
486 HILOG_ERROR("GetApplicationClient failed.");
487 return;
488 }
489 object->ScheduleANRProcess();
490 }
491
JudgeSelfCalledByRecordId(int32_t recordId)492 bool AppMgrService::JudgeSelfCalledByRecordId(int32_t recordId)
493 {
494 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
495 if (isSaCall) {
496 return true;
497 }
498
499 if (appMgrServiceInner_ == nullptr) {
500 return false;
501 }
502
503 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
504 std::shared_ptr<AppRunningRecord> appRecord = appMgrServiceInner_->GetAppRunningRecordByAppRecordId(recordId);
505 if (appRecord == nullptr || ((appRecord->GetApplicationInfo())->accessTokenId) != callingTokenId) {
506 HILOG_ERROR("Is not self, not enabled");
507 return false;
508 }
509
510 return true;
511 }
512 } // namespace AppExecFwk
513 } // namespace OHOS
514