• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2025 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 <parameters.h>
17 
18 #include "time_service_client.h"
19 #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE
20 #include "power_mgr_client.h"
21 #include "shutdown/shutdown_client.h"
22 #endif
23 #include "unistd.h"
24 #include "accesstoken_kit.h"
25 
26 #include "bundle_active_log.h"
27 #include "bundle_state_inner_errors.h"
28 #include "bundle_active_event.h"
29 #include "bundle_active_package_stats.h"
30 #include "bundle_active_account_helper.h"
31 #include "bundle_active_bundle_mgr_helper.h"
32 #include "bundle_active_shutdown_callback_service.h"
33 #include "tokenid_kit.h"
34 #include "xcollie/watchdog.h"
35 #include "bundle_active_util.h"
36 #include "bundle_active_report_controller.h"
37 #include "bundle_active_service.h"
38 
39 namespace OHOS {
40 namespace DeviceUsageStats {
41 using namespace OHOS::Security;
42 static const int32_t PERIOD_BEST_JS = 0;
43 static const int32_t PERIOD_YEARLY_JS = 4;
44 static const int32_t PERIOD_BEST_SERVICE = 4;
45 static const int32_t DELAY_TIME = 2000 * 1000;
46 static const std::string PERMITTED_PROCESS_NAME_FOUNDATION = "foundation";
47 static const std::string PERMITTED_PROCESS_NAME_RSS = "resource_schedule_service";
48 static const int32_t MAXNUM_UP_LIMIT = 1000;
49 const int32_t EVENTS_PARAM = 5;
50 static constexpr int32_t NO_DUMP_PARAM_NUMS = 0;
51 const int32_t PACKAGE_USAGE_PARAM = 6;
52 const int32_t MODULE_USAGE_PARAM = 4;
53 const int32_t HIGH_FREQUENCY_HOUR_USAGE_PARAM = 3;
54 const std::string NEEDED_PERMISSION = "ohos.permission.BUNDLE_ACTIVE_INFO";
55 const int32_t ENG_MODE = OHOS::system::GetIntParameter("const.debuggable", 0);
56 const bool REGISTER_RESULT =
57     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<BundleActiveService>::GetInstance().get());
58 
BundleActiveService()59 BundleActiveService::BundleActiveService() : SystemAbility(DEVICE_USAGE_STATISTICS_SYS_ABILITY_ID, true)
60 {
61 }
62 
~BundleActiveService()63 BundleActiveService::~BundleActiveService()
64 {
65 }
66 // LCOV_EXCL_START
OnStart()67 void BundleActiveService::OnStart()
68 {
69     BUNDLE_ACTIVE_LOGI("OnStart() called");
70     if (ready_) {
71         BUNDLE_ACTIVE_LOGI("service is ready. nothing to do.");
72         return;
73     }
74     std::shared_ptr<BundleActiveService> service = shared_from_this();
75     ffrt::submit([service]() {
76         service->InitNecessaryState();
77         });
78 }
79 
InitNecessaryState()80 void BundleActiveService::InitNecessaryState()
81 {
82     std::set<int32_t> serviceIdSets{
83         APP_MGR_SERVICE_ID, BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, POWER_MANAGER_SERVICE_ID, COMMON_EVENT_SERVICE_ID,
84         BACKGROUND_TASK_MANAGER_SERVICE_ID, TIME_SERVICE_ID,
85     };
86     sptr<ISystemAbilityManager> systemAbilityManager
87         = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
88     if (systemAbilityManager == nullptr) {
89         BUNDLE_ACTIVE_LOGI("GetSystemAbilityManager fail!");
90         std::shared_ptr<BundleActiveService> service = shared_from_this();
91         ffrt::submit([service]() {
92             service->InitNecessaryState();
93             }, ffrt::task_attr().delay(DELAY_TIME));
94         return;
95     }
96     for (const auto& serviceItem : serviceIdSets) {
97         auto checkResult = systemAbilityManager->CheckSystemAbility(serviceItem);
98         if (!checkResult) {
99             BUNDLE_ACTIVE_LOGI("request system service is not ready yet!");
100             std::shared_ptr<BundleActiveService> service = shared_from_this();
101             ffrt::submit([service]() {
102                 service->InitNecessaryState();
103                 }, ffrt::task_attr().delay(DELAY_TIME));
104             return;
105         }
106     }
107 
108     for (const auto& serviceItem : serviceIdSets) {
109         auto getAbility = systemAbilityManager->GetSystemAbility(serviceItem);
110         if (!getAbility) {
111             BUNDLE_ACTIVE_LOGI("request system service object is not ready yet!");
112             std::shared_ptr<BundleActiveService> service = shared_from_this();
113             ffrt::submit([service]() {
114                 service->InitNecessaryState();
115                 }, ffrt::task_attr().delay(DELAY_TIME));
116             return;
117         }
118     }
119     InitService();
120     ready_ = true;
121     int32_t ret = Publish(DelayedSingleton<BundleActiveService>::GetInstance().get());
122     if (!ret) {
123         BUNDLE_ACTIVE_LOGE("[Server] OnStart, Register SystemAbility[1907] FAIL.");
124         return;
125     }
126     BUNDLE_ACTIVE_LOGI("[Server] OnStart, Register SystemAbility[1907] SUCCESS.");
127 }
128 // LCOV_EXCL_STOP
InitService()129 void BundleActiveService::InitService()
130 {
131     if (bundleActiveCore_ == nullptr) {
132         bundleActiveCore_ = std::make_shared<BundleActiveCore>();
133         bundleActiveCore_->Init();
134     }
135     BundleActiveReportController::GetInstance().Init(bundleActiveCore_);
136     auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler();
137 // LCOV_EXCL_START
138     if (bundleActiveReportHandler == nullptr || bundleActiveCore_ == nullptr) {
139         return;
140     }
141 // LCOV_EXCL_STOP
142     BUNDLE_ACTIVE_LOGI("core and handler is not null");
143 #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE
144     shutdownCallback_ = new (std::nothrow) BundleActiveShutdownCallbackService(bundleActiveCore_);
145     powerStateCallback_ = new (std::nothrow) BundleActivePowerStateCallbackService(bundleActiveCore_);
146     auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
147     auto& shutdownClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
148     if (shutdownCallback_) {
149         shutdownClient.RegisterShutdownCallback(shutdownCallback_);
150     }
151     if (powerStateCallback_) {
152         powerManagerClient.RegisterPowerStateCallback(powerStateCallback_);
153     }
154 #endif
155     InitAppStateSubscriber();
156     InitContinuousSubscriber();
157     bundleActiveCore_->InitBundleGroupController();
158     SubscribeAppState();
159     SubscribeContinuousTask();
160 }
161 
GetAppManagerInstance()162 OHOS::sptr<OHOS::AppExecFwk::IAppMgr> BundleActiveService::GetAppManagerInstance()
163 {
164     OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
165         OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
166     OHOS::sptr<OHOS::IRemoteObject> object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
167 // LCOV_EXCL_START
168     if (!object) {
169         return nullptr;
170     }
171 // LCOV_EXCL_STOP
172     return OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(object);
173 }
174 
InitAppStateSubscriber()175 void BundleActiveService::InitAppStateSubscriber()
176 {
177     if (!appStateObserver_) {
178         appStateObserver_ = new (std::nothrow)BundleActiveAppStateObserver();
179 // LCOV_EXCL_START
180         if (!appStateObserver_) {
181             BUNDLE_ACTIVE_LOGE("malloc app state observer failed");
182             return;
183         }
184 // LCOV_EXCL_STOP
185     }
186 }
187 
InitContinuousSubscriber()188 void BundleActiveService::InitContinuousSubscriber()
189 {
190 #ifdef BGTASKMGR_ENABLE
191     if (continuousTaskObserver_ == nullptr) {
192         continuousTaskObserver_ = std::make_shared<BundleActiveContinuousTaskObserver>();
193     }
194 #endif
195 }
196 
SubscribeAppState()197 bool BundleActiveService::SubscribeAppState()
198 {
199     sptr<OHOS::AppExecFwk::IAppMgr> appManager = GetAppManagerInstance();
200 // LCOV_EXCL_START
201     if (appStateObserver_ == nullptr || appManager == nullptr) {
202         BUNDLE_ACTIVE_LOGE("SubscribeAppState appstateobserver is null, return");
203         return false;
204     }
205 // LCOV_EXCL_STOP
206     int32_t err = appManager->RegisterApplicationStateObserver(appStateObserver_);
207     if (err != 0) {
208         BUNDLE_ACTIVE_LOGE("RegisterApplicationStateObserver failed. err:%{public}d", err);
209         return false;
210     }
211 // LCOV_EXCL_START
212     BUNDLE_ACTIVE_LOGD("RegisterApplicationStateObserver success.");
213     return true;
214 // LCOV_EXCL_STOP
215 }
216 
SubscribeContinuousTask()217 bool BundleActiveService::SubscribeContinuousTask()
218 {
219 #ifdef BGTASKMGR_ENABLE
220     if (continuousTaskObserver_ == nullptr) {
221         BUNDLE_ACTIVE_LOGE("SubscribeContinuousTask continuousTaskObserver_ is null, return");
222         return false;
223     }
224     ErrCode errCode = BackgroundTaskMgr::BackgroundTaskMgrHelper::SubscribeBackgroundTask(*continuousTaskObserver_);
225 // LCOV_EXCL_START
226     if (errCode != ERR_OK) {
227         BUNDLE_ACTIVE_LOGE("SubscribeBackgroundTask failed.");
228         return false;
229     }
230 // LCOV_EXCL_STOP
231 #endif
232     return true;
233 }
234 
235 // LCOV_EXCL_START
OnStop()236 void BundleActiveService::OnStop()
237 {
238 #ifdef DEVICE_USAGES_STATISTICS_POWERMANGER_ENABLE
239     if (shutdownCallback_ != nullptr) {
240         auto& shutdownClient = OHOS::PowerMgr::ShutdownClient::GetInstance();
241         auto& powerManagerClient = OHOS::PowerMgr::PowerMgrClient::GetInstance();
242         shutdownClient.UnRegisterShutdownCallback(shutdownCallback_);
243         powerManagerClient.UnRegisterPowerStateCallback(powerStateCallback_);
244         return;
245     }
246 #endif
247     bundleActiveCore_->DeInit();
248     BUNDLE_ACTIVE_LOGI("[Server] OnStop");
249     ready_ = false;
250 }
251 // LCOV_EXCL_STOP
252 
ReportEvent(const BundleActiveEvent & event,int32_t userId)253 ErrCode BundleActiveService::ReportEvent(const BundleActiveEvent& event, int32_t userId)
254 {
255     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
256     if (CheckNativePermission(tokenId) != ERR_OK) {
257         BUNDLE_ACTIVE_LOGE("token does not belong to native process, return");
258         return ERR_PERMISSION_DENIED;
259     }
260 
261     AccessToken::NativeTokenInfo callingTokenInfo;
262     AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, callingTokenInfo);
263     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
264     BUNDLE_ACTIVE_LOGD("calling process name is %{public}s, uid is %{public}d",
265         callingTokenInfo.processName.c_str(), callingUid);
266     if (callingTokenInfo.processName != PERMITTED_PROCESS_NAME_FOUNDATION &&
267         callingTokenInfo.processName != PERMITTED_PROCESS_NAME_RSS) {
268         BUNDLE_ACTIVE_LOGE("token does not belong to fms service process, return");
269         return ERR_PERMISSION_DENIED;
270     }
271 // LCOV_EXCL_START
272     BundleActiveReportHandlerObject tmpHandlerObject(userId, "");
273     BundleActiveEvent eventNew(event);
274     tmpHandlerObject.event_ = eventNew;
275     sptr<MiscServices::TimeServiceClient> timer = MiscServices::TimeServiceClient::GetInstance();
276     tmpHandlerObject.event_.timeStamp_ = timer->GetBootTimeMs();
277     std::shared_ptr<BundleActiveReportHandlerObject> handlerobjToPtr =
278         std::make_shared<BundleActiveReportHandlerObject>(tmpHandlerObject);
279     auto bundleActiveReportHandler = BundleActiveReportController::GetInstance().GetBundleReportHandler();
280     if (bundleActiveReportHandler == nullptr) {
281         return ERR_OK;
282     }
283     bundleActiveReportHandler->SendEvent(BundleActiveReportHandler::MSG_REPORT_EVENT, handlerobjToPtr);
284     return ERR_OK;
285 // LCOV_EXCL_STOP
286 }
287 
IsBundleIdle(bool & isBundleIdle,const std::string & bundleName,int32_t userId)288 ErrCode BundleActiveService::IsBundleIdle(bool& isBundleIdle, const std::string& bundleName, int32_t userId)
289 {
290     // get uid
291     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
292     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
293     ErrCode ret = ERR_OK;
294     std::string callingBundleName = "";
295     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, callingBundleName);
296     BUNDLE_ACTIVE_LOGI("UID is %{public}d, bundle name is %{public}s", callingUid, callingBundleName.c_str());
297     // get user id
298     int32_t result = -1;
299     if (userId == -1) {
300         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
301 // LCOV_EXCL_START
302         if (ret != ERR_OK || userId == -1) {
303             return ret;
304         }
305 // LCOV_EXCL_STOP
306     }
307 
308     if (callingBundleName == bundleName) {
309         if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
310             BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
311             return ERR_NOT_SYSTEM_APP;
312         }
313 // LCOV_EXCL_START
314         BUNDLE_ACTIVE_LOGI("%{public}s check its own idle state", bundleName.c_str());
315         result = bundleActiveCore_->IsBundleIdle(bundleName, userId);
316 // LCOV_EXCL_STOP
317     } else {
318         ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
319         if (ret == ERR_OK) {
320             result = bundleActiveCore_->IsBundleIdle(bundleName, userId);
321         } else {
322             return ret;
323         }
324     }
325 // LCOV_EXCL_START
326     if (result == 0 || result == -1) {
327         isBundleIdle = false;
328     } else {
329         isBundleIdle = true;
330     }
331 // LCOV_EXCL_STOP
332     return ERR_OK;
333 }
334 
IsBundleUsePeriod(bool & IsUsePeriod,const std::string & bundleName,int32_t userId)335 ErrCode BundleActiveService::IsBundleUsePeriod(bool& IsUsePeriod, const std::string& bundleName, int32_t userId)
336 {
337     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
338     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
339     if (AccessToken::AccessTokenKit::GetTokenType(tokenId) != AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
340         return ERR_PERMISSION_DENIED;
341     }
342     auto ret = CheckNativePermission(tokenId);
343 // LCOV_EXCL_START
344     if (ret != ERR_OK) {
345         return ret;
346     }
347 // LCOV_EXCL_STOP
348     if (userId == -1) {
349         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
350 // LCOV_EXCL_START
351         if (ret != ERR_OK || userId == -1) {
352             return ret;
353         }
354 // LCOV_EXCL_STOP
355     }
356     IsUsePeriod = bundleActiveCore_->IsBundleUsePeriod(bundleName, userId);
357     BUNDLE_ACTIVE_LOGI("IsBundleUsePeriod %{public}d", IsUsePeriod);
358     return ERR_OK;
359 }
360 
QueryBundleStatsInfoByInterval(std::vector<BundleActivePackageStats> & packageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime,int32_t userId)361 ErrCode BundleActiveService::QueryBundleStatsInfoByInterval(std::vector<BundleActivePackageStats>& packageStats,
362     const int32_t intervalType, const int64_t beginTime, const int64_t endTime, int32_t userId)
363 {
364     BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfoByInterval stats called, intervaltype is %{public}d", intervalType);
365     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
366     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
367     ErrCode ret = ERR_OK;
368     if (userId == -1) {
369         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
370 // LCOV_EXCL_START
371         if (ret != ERR_OK || userId == -1) {
372             return ret;
373         }
374 // LCOV_EXCL_STOP
375     }
376     BUNDLE_ACTIVE_LOGI("QueryBundleStatsInfos user id is %{public}d", userId);
377     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
378     if (ret != ERR_OK) {
379         return ret;
380     }
381     std::vector<BundleActivePackageStats> tempPackageStats;
382     int32_t convertedIntervalType = ConvertIntervalType(intervalType);
383     ret = bundleActiveCore_->QueryBundleStatsInfos(
384         tempPackageStats, userId, convertedIntervalType, beginTime, endTime, "");
385 // LCOV_EXCL_START
386     for (auto& packageStat : tempPackageStats) {
387         packageStat.appIndex_ = GetNameAndIndexForUid(packageStat.uid_);
388     }
389 // LCOV_EXCL_STOP
390     packageStats = MergePackageStats(tempPackageStats);
391     return ret;
392 }
393 
GetNameAndIndexForUid(int32_t uid)394 int32_t BundleActiveService::GetNameAndIndexForUid(int32_t uid)
395 {
396     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
397 // LCOV_EXCL_START
398     if (systemAbilityManager == nullptr) {
399         BUNDLE_ACTIVE_LOGE("failed to get samgr");
400         return -1;
401     }
402 // LCOV_EXCL_STOP
403 
404     sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
405 // LCOV_EXCL_START
406     if (remoteObject == nullptr) {
407         BUNDLE_ACTIVE_LOGE("failed to get bundle manager service");
408         return -1;
409     }
410 // LCOV_EXCL_STOP
411     sptr<AppExecFwk::IBundleMgr> bundleManager = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
412     int32_t appIndex = -1;
413     if (bundleManager != nullptr) {
414         std::string bundleName;
415         bundleManager->GetNameAndIndexForUid(uid, bundleName, appIndex);
416     }
417     return appIndex;
418 }
419 
QueryBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime,int32_t userId)420 ErrCode BundleActiveService::QueryBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
421     const int64_t beginTime, const int64_t endTime, int32_t userId)
422 {
423     ErrCode ret = ERR_OK;
424     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
425     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
426     if (userId == -1) {
427         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
428 // LCOV_EXCL_START
429         if (ret != ERR_OK || userId == -1) {
430             return ret;
431         }
432 // LCOV_EXCL_STOP
433     }
434     BUNDLE_ACTIVE_LOGI("QueryBundleEvents userid is %{public}d", userId);
435     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
436     if (ret == ERR_OK) {
437         ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, "");
438         BUNDLE_ACTIVE_LOGI("QueryBundleEvents result is %{public}zu", bundleActiveEvents.size());
439     }
440     return ret;
441 }
442 
QueryHighFrequencyPeriodBundle(std::vector<BundleActiveHighFrequencyPeriod> & appFreqHours,int32_t userId)443 ErrCode BundleActiveService::QueryHighFrequencyPeriodBundle(
444     std::vector<BundleActiveHighFrequencyPeriod>& appFreqHours, int32_t userId)
445 {
446     ErrCode ret = ERR_OK;
447     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
448     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
449     if (userId == -1) {
450         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
451 // LCOV_EXCL_START
452         if (ret != ERR_OK || userId == -1) {
453             return ret;
454         }
455 // LCOV_EXCL_STOP
456     }
457     BUNDLE_ACTIVE_LOGI("QueryHighFrequencyPeriodBundle userid is %{public}d", userId);
458     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
459 // LCOV_EXCL_START
460     if (ret == ERR_OK) {
461         ret = bundleActiveCore_->QueryHighFrequencyPeriodBundle(appFreqHours, userId);
462         BUNDLE_ACTIVE_LOGI("QueryHighFrequencyPeriodBundle result is %{public}zu", appFreqHours.size());
463     }
464 // LCOV_EXCL_STOP
465     return ret;
466 }
467 
QueryBundleTodayLatestUsedTime(int64_t & latestUsedTime,const std::string & bundleName,int32_t userId)468 ErrCode BundleActiveService::QueryBundleTodayLatestUsedTime(
469     int64_t& latestUsedTime, const std::string& bundleName, int32_t userId)
470 {
471     ErrCode ret = ERR_OK;
472     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
473     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
474     if (userId == -1) {
475         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
476 // LCOV_EXCL_START
477         if (ret != ERR_OK || userId == -1) {
478             return ret;
479         }
480 // LCOV_EXCL_STOP
481     }
482     BUNDLE_ACTIVE_LOGI("QueryBundleTodayLatestUsedTime userid is %{public}d", userId);
483     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
484 // LCOV_EXCL_START
485     if (ret != ERR_OK) {
486         return ret;
487     }
488 // LCOV_EXCL_STOP
489     int64_t currentSystemTime = BundleActiveUtil::GetSystemTimeMs();
490     int64_t startTime = BundleActiveUtil::GetIntervalTypeStartTime(currentSystemTime, BundleActiveUtil::PERIOD_DAILY);
491     std::vector<BundleActivePackageStats> packageStats;
492     ret = bundleActiveCore_->QueryBundleStatsInfos(
493         packageStats, userId, BundleActiveUtil::PERIOD_DAILY, startTime, currentSystemTime, bundleName);
494     if (ret != ERR_OK) {
495         return ret;
496     }
497     auto bundleActivePackageStats = MergePackageStats(packageStats);
498     if (bundleActivePackageStats.empty() || bundleActivePackageStats[0].bundleName_ != bundleName) {
499         return ERR_NO_APP_GROUP_INFO_IN_DATABASE;
500     }
501     latestUsedTime = bundleActivePackageStats[0].lastTimeUsed_;
502     return ret;
503 }
504 
SetAppGroup(const std::string & bundleName,int32_t newGroup,int32_t userId)505 ErrCode BundleActiveService::SetAppGroup(const std::string& bundleName, int32_t newGroup, int32_t userId)
506 {
507     ErrCode ret = ERR_OK;
508     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
509     bool isFlush = false;
510     if (userId == -1) {
511         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
512 // LCOV_EXCL_START
513         if (ret != ERR_OK || userId == -1) {
514             return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
515         }
516 // LCOV_EXCL_STOP
517         isFlush = true;
518     }
519     BUNDLE_ACTIVE_LOGI("SetAppGroup userId is %{public}d", userId);
520 
521     std::string localBundleName = "";
522     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
523     if (localBundleName == bundleName) {
524         BUNDLE_ACTIVE_LOGI("SetAppGroup can not set its bundleName");
525         return ERR_PERMISSION_DENIED;
526     }
527     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
528     ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
529 // LCOV_EXCL_START
530     if (ret == ERR_OK) {
531         ret = bundleActiveCore_->SetAppGroup(bundleName, newGroup, userId, isFlush);
532     }
533 // LCOV_EXCL_STOP
534     return ret;
535 }
536 
QueryBundleStatsInfos(std::vector<BundleActivePackageStats> & bundleActivePackageStats,const int32_t intervalType,const int64_t beginTime,const int64_t endTime)537 ErrCode BundleActiveService::QueryBundleStatsInfos(std::vector<BundleActivePackageStats>& bundleActivePackageStats,
538     const int32_t intervalType, const int64_t beginTime, const int64_t endTime)
539 {
540     // get uid
541     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
542     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
543     BUNDLE_ACTIVE_LOGD("UID is %{public}d", callingUid);
544     // get userid
545     int32_t userId = -1;
546     ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
547 // LCOV_EXCL_START
548     if (ret != ERR_OK || userId == -1) {
549         return ret;
550     }
551 // LCOV_EXCL_STOP
552     std::vector<BundleActivePackageStats> tempPackageStats;
553     BUNDLE_ACTIVE_LOGD("QueryBundleStatsInfos userid is %{public}d", userId);
554     std::string bundleName = "";
555     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
556     ErrCode isSystemAppAndHasPermission = CheckBundleIsSystemAppAndHasPermission(callingUid, tokenId);
557     if (!bundleName.empty() && isSystemAppAndHasPermission == ERR_OK) {
558 // LCOV_EXCL_START
559         int32_t convertedIntervalType = ConvertIntervalType(intervalType);
560         ret = bundleActiveCore_->QueryBundleStatsInfos(tempPackageStats, userId, convertedIntervalType,
561             beginTime, endTime, bundleName);
562     }
563 // LCOV_EXCL_STOP
564     bundleActivePackageStats = MergePackageStats(tempPackageStats);
565     return ret;
566 }
567 
QueryCurrentBundleEvents(std::vector<BundleActiveEvent> & bundleActiveEvents,const int64_t beginTime,const int64_t endTime)568 ErrCode BundleActiveService::QueryCurrentBundleEvents(std::vector<BundleActiveEvent>& bundleActiveEvents,
569     const int64_t beginTime, const int64_t endTime)
570 {
571     // get uid
572     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
573     BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents UID is %{public}d", callingUid);
574     // get userid
575     int32_t userId = -1;
576     ErrCode ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
577     if (ret == ERR_OK && userId != -1) {
578         std::string bundleName = "";
579         BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, bundleName);
580 // LCOV_EXCL_START
581         if (!bundleName.empty()) {
582             if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
583                 BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
584                 return ERR_NOT_SYSTEM_APP;
585             }
586             BUNDLE_ACTIVE_LOGI("QueryCurrentBundleEvents buindle name is %{public}s",
587                 bundleName.c_str());
588             ret = bundleActiveCore_->QueryBundleEvents(bundleActiveEvents, userId, beginTime, endTime, bundleName);
589         }
590 // LCOV_EXCL_STOP
591     }
592     BUNDLE_ACTIVE_LOGD("QueryCurrentBundleEvents bundleActiveEvents size is %{public}zu", bundleActiveEvents.size());
593     return ret;
594 }
595 
QueryAppGroup(int32_t & appGroup,const std::string & bundleName,int32_t userId)596 ErrCode BundleActiveService::QueryAppGroup(int32_t& appGroup, const std::string& bundleName, int32_t userId)
597 {
598     // get uid
599     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
600     BUNDLE_ACTIVE_LOGD("QueryAppGroup UID is %{public}d", callingUid);
601     ErrCode ret = ERR_OK;
602     if (userId == -1) {
603         ret = BundleActiveAccountHelper::GetUserId(callingUid, userId);
604 // LCOV_EXCL_START
605         if (ret != ERR_OK || userId == -1) {
606             return ERR_SYSTEM_ABILITY_SUPPORT_FAILED;
607         }
608 // LCOV_EXCL_STOP
609     }
610     if (bundleName.empty()) {
611         std::string localBundleName = "";
612         BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(callingUid, localBundleName);
613         if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
614             BUNDLE_ACTIVE_LOGE("%{public}s is not system app", localBundleName.c_str());
615             return ERR_NOT_SYSTEM_APP;
616         }
617 // LCOV_EXCL_START
618         ret = bundleActiveCore_->QueryAppGroup(appGroup, localBundleName, userId);
619 // LCOV_EXCL_STOP
620     } else {
621         AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
622         ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
623         if (ret == ERR_OK) {
624             ret = bundleActiveCore_->QueryAppGroup(appGroup, bundleName, userId);
625         }
626     }
627     return ret;
628 }
629 
RegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)630 ErrCode BundleActiveService::RegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
631 {
632 // LCOV_EXCL_START
633     if (!bundleActiveCore_) {
634         return ERR_MEMORY_OPERATION_FAILED;
635     }
636 // LCOV_EXCL_STOP
637     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
638     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
639     ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
640     if (ret == ERR_OK) {
641         ret = bundleActiveCore_->RegisterAppGroupCallBack(tokenId, observer);
642     }
643     return ret;
644 }
645 
UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> & observer)646 ErrCode BundleActiveService::UnRegisterAppGroupCallBack(const sptr<IAppGroupCallback> &observer)
647 {
648     if (!bundleActiveCore_) {
649         return ERR_MEMORY_OPERATION_FAILED;
650     }
651     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
652     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
653     ErrCode ret = CheckSystemAppOrNativePermission(callingUid, tokenId);
654     if (ret == ERR_OK) {
655         ret = bundleActiveCore_->UnRegisterAppGroupCallBack(tokenId, observer);
656     }
657     return ret;
658 }
659 
ConvertIntervalType(const int32_t intervalType)660 int32_t BundleActiveService::ConvertIntervalType(const int32_t intervalType)
661 {
662     if (intervalType == PERIOD_BEST_JS) {
663         return PERIOD_BEST_SERVICE;
664     } else if (intervalType > PERIOD_BEST_JS && intervalType <= PERIOD_YEARLY_JS) {
665         return intervalType - 1;
666     }
667     return -1;
668 }
669 
CheckBundleIsSystemAppAndHasPermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)670 ErrCode BundleActiveService::CheckBundleIsSystemAppAndHasPermission(const int32_t uid,
671     OHOS::Security::AccessToken::AccessTokenID tokenId)
672 {
673     std::string bundleName = "";
674     BundleActiveBundleMgrHelper::GetInstance()->GetNameForUid(uid, bundleName);
675 
676     if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) {
677         BUNDLE_ACTIVE_LOGE("%{public}s is not system app", bundleName.c_str());
678         return ERR_NOT_SYSTEM_APP;
679     }
680 // LCOV_EXCL_START
681     int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
682     if (bundleHasPermission != 0) {
683         BUNDLE_ACTIVE_LOGE("%{public}s hasn't permission", bundleName.c_str());
684         return ERR_PERMISSION_DENIED;
685     }
686     BUNDLE_ACTIVE_LOGI("%{public}s has permission", bundleName.c_str());
687     return ERR_OK;
688 // LCOV_EXCL_STOP
689 }
690 
CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)691 ErrCode BundleActiveService::CheckNativePermission(OHOS::Security::AccessToken::AccessTokenID tokenId)
692 {
693     int32_t bundleHasPermission = AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, NEEDED_PERMISSION);
694     if (bundleHasPermission != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
695         BUNDLE_ACTIVE_LOGE("check native permission not have permission");
696         return ERR_PERMISSION_DENIED;
697     }
698     auto tokenFlag = AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
699     if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_NATIVE) {
700         return ERR_OK;
701     }
702 // LCOV_EXCL_START
703     if (tokenFlag == AccessToken::TypeATokenTypeEnum::TOKEN_SHELL) {
704         return ERR_OK;
705     }
706     return ERR_PERMISSION_DENIED;
707 // LCOV_EXCL_STOP
708 }
709 
CheckSystemAppOrNativePermission(const int32_t uid,OHOS::Security::AccessToken::AccessTokenID tokenId)710 ErrCode BundleActiveService::CheckSystemAppOrNativePermission(const int32_t uid,
711     OHOS::Security::AccessToken::AccessTokenID tokenId)
712 {
713 // LCOV_EXCL_START
714     if (AccessToken::AccessTokenKit::GetTokenType(tokenId) == AccessToken::ATokenTypeEnum::TOKEN_HAP) {
715         return CheckBundleIsSystemAppAndHasPermission(uid, tokenId);
716     }
717 // LCOV_EXCL_STOP
718     return CheckNativePermission(tokenId);
719 }
720 
QueryModuleUsageRecords(int32_t maxNum,std::vector<BundleActiveModuleRecord> & results,int32_t userId)721 ErrCode BundleActiveService::QueryModuleUsageRecords(int32_t maxNum, std::vector<BundleActiveModuleRecord>& results,
722     int32_t userId)
723 {
724     ErrCode errCode = ERR_OK;
725     if (maxNum > MAXNUM_UP_LIMIT || maxNum <= 0) {
726         BUNDLE_ACTIVE_LOGE("MaxNum is Invalid!");
727         return ERR_FIND_APP_USAGE_RECORDS_FAILED;
728     }
729     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
730     if (userId == -1) {
731         errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
732 // LCOV_EXCL_START
733         if (errCode != ERR_OK || userId == -1) {
734             return errCode;
735         }
736 // LCOV_EXCL_STOP
737     }
738     BUNDLE_ACTIVE_LOGI("QueryModuleUsageRecords userid is %{public}d", userId);
739     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
740     errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
741 // LCOV_EXCL_START
742     if (errCode == ERR_OK) {
743         errCode = bundleActiveCore_->QueryModuleUsageRecords(maxNum, results, userId);
744         for (auto& oneResult : results) {
745             QueryModuleRecordInfos(oneResult);
746         }
747     }
748 // LCOV_EXCL_STOP
749     return errCode;
750 }
751 
QueryDeviceEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)752 ErrCode BundleActiveService::QueryDeviceEventStats(int64_t beginTime, int64_t endTime,
753     std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
754 {
755     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
756     ErrCode errCode = ERR_OK;
757     if (userId == -1) {
758         errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
759 // LCOV_EXCL_START
760         if (errCode != ERR_OK || userId == -1) {
761             return errCode;
762         }
763 // LCOV_EXCL_STOP
764     }
765     BUNDLE_ACTIVE_LOGI("QueryDeviceEventStats userid is %{public}d", userId);
766     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
767     errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
768     if (errCode == ERR_OK) {
769         errCode = bundleActiveCore_->QueryDeviceEventStats(beginTime, endTime, eventStats, userId);
770     }
771     BUNDLE_ACTIVE_LOGD("QueryDeviceEventStats result size is %{public}zu", eventStats.size());
772     return errCode;
773 }
774 
QueryNotificationEventStats(int64_t beginTime,int64_t endTime,std::vector<BundleActiveEventStats> & eventStats,int32_t userId)775 ErrCode BundleActiveService::QueryNotificationEventStats(int64_t beginTime, int64_t endTime,
776     std::vector<BundleActiveEventStats>& eventStats, int32_t userId)
777 {
778     int32_t callingUid = OHOS::IPCSkeleton::GetCallingUid();
779     BUNDLE_ACTIVE_LOGD("QueryNotificationEventStats UID is %{public}d", callingUid);
780     // get userid when userId is -1
781     ErrCode errCode = ERR_OK;
782     if (userId == -1) {
783         errCode = BundleActiveAccountHelper::GetUserId(callingUid, userId);
784 // LCOV_EXCL_START
785         if (errCode != ERR_OK || userId == -1) {
786             return errCode;
787         }
788 // LCOV_EXCL_STOP
789     }
790     BUNDLE_ACTIVE_LOGI("QueryNotificationEventStats userid is %{public}d", userId);
791     AccessToken::AccessTokenID tokenId = OHOS::IPCSkeleton::GetCallingTokenID();
792     errCode = CheckSystemAppOrNativePermission(callingUid, tokenId);
793     if (errCode == ERR_OK) {
794         errCode = bundleActiveCore_->QueryNotificationEventStats(beginTime, endTime, eventStats, userId);
795     }
796     return errCode;
797 }
798 
QueryModuleRecordInfos(BundleActiveModuleRecord & moduleRecord)799 void BundleActiveService::QueryModuleRecordInfos(BundleActiveModuleRecord& moduleRecord)
800 {
801     ApplicationInfo appInfo;
802     bool getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetApplicationInfo(moduleRecord.bundleName_,
803         ApplicationFlag::GET_BASIC_APPLICATION_INFO, moduleRecord.userId_, appInfo);
804     if (!getInfoIsSuccess) {
805         BUNDLE_ACTIVE_LOGE("GetApplicationInfo failed!");
806         return;
807     }
808 // LCOV_EXCL_START
809     BundleInfo bundleInfo;
810     getInfoIsSuccess = BundleActiveBundleMgrHelper::GetInstance()->GetBundleInfo(moduleRecord.bundleName_,
811         BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO, bundleInfo, moduleRecord.userId_);
812     if (!getInfoIsSuccess) {
813         BUNDLE_ACTIVE_LOGE("GetBundleInfo failed!");
814         return;
815     }
816     for (const auto& oneModuleInfo : bundleInfo.hapModuleInfos) {
817         if (oneModuleInfo.moduleName == moduleRecord.moduleName_) {
818             std::string mainAbility = oneModuleInfo.mainAbility;
819             for (auto oneAbilityInfo : oneModuleInfo.abilityInfos) {
820                 if (oneAbilityInfo.type != AbilityType::PAGE) {
821                     continue;
822                 }
823                 if (mainAbility.empty() || mainAbility.compare(oneAbilityInfo.name) == 0) {
824                     SerModuleProperties(oneModuleInfo, appInfo, oneAbilityInfo, moduleRecord);
825                     break;
826                 }
827             }
828         }
829     }
830 // LCOV_EXCL_STOP
831 }
832 
SerModuleProperties(const HapModuleInfo & hapModuleInfo,const ApplicationInfo & appInfo,const AbilityInfo & abilityInfo,BundleActiveModuleRecord & moduleRecord)833 void BundleActiveService::SerModuleProperties(const HapModuleInfo& hapModuleInfo,
834     const ApplicationInfo& appInfo, const AbilityInfo& abilityInfo, BundleActiveModuleRecord& moduleRecord)
835 {
836     moduleRecord.deviceId_ = appInfo.deviceId;
837     moduleRecord.abilityName_ = abilityInfo.name;
838     moduleRecord.appLabelId_ = appInfo.labelId;
839     moduleRecord.labelId_ = static_cast<uint32_t>(hapModuleInfo.labelId);
840     moduleRecord.abilityLableId_ = abilityInfo.labelId;
841     moduleRecord.descriptionId_ = abilityInfo.descriptionId;
842     moduleRecord.abilityIconId_ = abilityInfo.iconId;
843     moduleRecord.installFreeSupported_ = hapModuleInfo.installationFree;
844 }
845 
AllowDump()846 bool BundleActiveService::AllowDump()
847 {
848 // LCOV_EXCL_START
849     if (ENG_MODE == 0) {
850         BUNDLE_ACTIVE_LOGE("Not eng mode");
851         return false;
852     }
853 // LCOV_EXCL_STOP
854     Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetFirstTokenID();
855     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenId, "ohos.permission.DUMP");
856     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
857         BUNDLE_ACTIVE_LOGE("CheckPermission failed");
858         return false;
859     }
860     return true;
861 }
862 
Dump(int32_t fd,const std::vector<std::u16string> & args)863 int32_t BundleActiveService::Dump(int32_t fd, const std::vector<std::u16string> &args)
864 {
865     if (!AllowDump()) {
866         return ERR_PERMISSION_DENIED;
867     }
868 // LCOV_EXCL_START
869     std::vector<std::string> argsInStr;
870     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr),
871         [](const std::u16string &arg) {
872         return Str16ToStr8(arg);
873     });
874     std::string result;
875     int32_t ret = ERR_OK;
876     if (argsInStr.size() == NO_DUMP_PARAM_NUMS) {
877         DumpUsage(result);
878     } else {
879         std::vector<std::string> infos;
880         if (argsInStr[0] == "-h") {
881             DumpUsage(result);
882         } else if (argsInStr[0] == "-A") {
883             ret = ShellDump(argsInStr, infos);
884         } else {
885             infos.emplace_back("BundleActiveService Error params.\n");
886             ret = ERR_USAGE_STATS_INVALID_PARAM;
887         }
888         for (auto info : infos) {
889             result.append(info);
890         }
891     }
892     if (!SaveStringToFd(fd, result)) {
893         BUNDLE_ACTIVE_LOGE("BundleActiveService dump save string to fd failed!");
894         ret = ERR_USAGE_STATS_METHOD_CALLED_FAILED;
895     }
896     return ret;
897 // LCOV_EXCL_STOP
898 }
899 
ShellDump(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)900 int32_t BundleActiveService::ShellDump(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
901 {
902     int32_t ret = -1;
903     if (!bundleActiveCore_) {
904         return ret;
905     }
906     if (dumpOption[1] == "Events") {
907         ret = DumpEvents(dumpOption, dumpInfo);
908     } else if (dumpOption[1] == "PackageUsage") {
909         ret = DumpPackageUsage(dumpOption, dumpInfo);
910     } else if (dumpOption[1] == "ModuleUsage") {
911         ret = DumpModuleUsage(dumpOption, dumpInfo);
912     } else if (dumpOption[1] == "HighFreqHourUsage") {
913         ret = DumpHighFreqHourUsage(dumpOption, dumpInfo);
914     }
915     return ret;
916 }
917 
DumpEvents(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)918 int32_t BundleActiveService::DumpEvents(const std::vector<std::string> &dumpOption, std::vector<std::string> &dumpInfo)
919 {
920     int32_t ret = -1;
921     std::vector<BundleActiveEvent> eventResult;
922     if (static_cast<int32_t>(dumpOption.size()) != EVENTS_PARAM) {
923         return ret;
924     }
925 // LCOV_EXCL_START
926     int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[2]);
927     int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[3]);
928     int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[4]);
929     bundleActiveCore_->QueryBundleEvents(eventResult, userId, beginTime, endTime, "");
930     for (auto& oneEvent : eventResult) {
931         dumpInfo.emplace_back(oneEvent.ToString());
932     }
933     return ret;
934 // LCOV_EXCL_STOP
935 }
936 
DumpPackageUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)937 int32_t BundleActiveService::DumpPackageUsage(const std::vector<std::string> &dumpOption,
938     std::vector<std::string> &dumpInfo)
939 {
940     int32_t ret = -1;
941     std::vector<BundleActivePackageStats> tempPackageUsage;
942 // LCOV_EXCL_START
943     if (static_cast<int32_t>(dumpOption.size()) != PACKAGE_USAGE_PARAM) {
944         return ret;
945     }
946 // LCOV_EXCL_STOP
947     int32_t intervalType = ConvertIntervalType(BundleActiveUtil::StringToInt32(dumpOption[2]));
948     int64_t beginTime = BundleActiveUtil::StringToInt64(dumpOption[3]);
949     int64_t endTime = BundleActiveUtil::StringToInt64(dumpOption[4]);
950     int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[5]);
951     bundleActiveCore_->QueryBundleStatsInfos(
952         tempPackageUsage, userId, intervalType, beginTime, endTime, "");
953     auto packageUsageResult = MergePackageStats(tempPackageUsage);
954 // LCOV_EXCL_START
955     for (auto& onePackageRecord : packageUsageResult) {
956         dumpInfo.emplace_back(onePackageRecord.ToString());
957     }
958 // LCOV_EXCL_STOP
959     return ret;
960 }
961 
DumpModuleUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)962 int32_t BundleActiveService::DumpModuleUsage(const std::vector<std::string> &dumpOption,
963     std::vector<std::string> &dumpInfo)
964 {
965     int32_t ret = -1;
966     std::vector<BundleActiveModuleRecord> moduleResult;
967     if (static_cast<int32_t>(dumpOption.size()) != MODULE_USAGE_PARAM) {
968         return ret;
969     }
970 // LCOV_EXCL_START
971     int32_t maxNum = BundleActiveUtil::StringToInt32(dumpOption[2]);
972     int32_t userId = BundleActiveUtil::StringToInt32(dumpOption[3]);
973     BUNDLE_ACTIVE_LOGI("M is %{public}d, u is %{public}d", maxNum, userId);
974     ret = bundleActiveCore_->QueryModuleUsageRecords(maxNum, moduleResult, userId);
975     for (auto& oneResult : moduleResult) {
976         QueryModuleRecordInfos(oneResult);
977     }
978     for (auto& oneModuleRecord : moduleResult) {
979         dumpInfo.emplace_back(oneModuleRecord.ToString());
980         for (uint32_t i = 0; i < oneModuleRecord.formRecords_.size(); i++) {
981             std::string oneFormInfo = "form " + std::to_string(static_cast<int32_t>(i) + 1) + ", ";
982             dumpInfo.emplace_back(oneFormInfo + oneModuleRecord.formRecords_[i].ToString());
983         }
984     }
985     return ret;
986 // LCOV_EXCL_STOP
987 }
988 
DumpHighFreqHourUsage(const std::vector<std::string> & dumpOption,std::vector<std::string> & dumpInfo)989 int32_t BundleActiveService::DumpHighFreqHourUsage(const std::vector<std::string>& dumpOption,
990     std::vector<std::string>& dumpInfo)
991 {
992     int32_t ret = -1;
993     if (static_cast<int32_t>(dumpOption.size()) != HIGH_FREQUENCY_HOUR_USAGE_PARAM) {
994         return ret;
995     }
996 // LCOV_EXCL_START
997     int32_t userId = BundleActiveUtil::StringToInt64(dumpOption[2]);
998     std::vector<BundleActiveHighFrequencyPeriod> appFreqHours;
999     ret = bundleActiveCore_->QueryHighFrequencyPeriodBundle(appFreqHours, userId);
1000     dumpInfo.emplace_back("appFreqHour size " + std::to_string(appFreqHours.size()) + "\n");
1001     for (auto& appFreqHour : appFreqHours) {
1002         dumpInfo.emplace_back(appFreqHour.ToString());
1003     }
1004     return ret;
1005 // LCOV_EXCL_STOP
1006 }
1007 
DumpUsage(std::string & result)1008 void BundleActiveService::DumpUsage(std::string &result)
1009 {
1010     std::string dumpHelpMsg =
1011         "usage: bundleactive dump [<options>]\n"
1012         "options list:\n"
1013         "  -h                                                             help menu\n"
1014         "  -A                                                                                    \n"
1015         "      Events [beginTime] [endTime] [userId]                      get events for one user\n"
1016         "      PackageUsage [intervalType] [beginTime] [endTime] [userId] get package usage for one user\n"
1017         "      ModuleUsage [maxNum] [userId]                              get module usage for one user\n";
1018     result.append(dumpHelpMsg);
1019 }
1020 // LCOV_EXCL_START
MergePackageStats(const std::vector<BundleActivePackageStats> & packageStats)1021 std::vector<BundleActivePackageStats> BundleActiveService::MergePackageStats(
1022     const std::vector<BundleActivePackageStats>& packageStats)
1023 {
1024     if (packageStats.empty()) {
1025         return packageStats;
1026     }
1027     std::vector<BundleActivePackageStats> tempPackageStats;
1028     std::shared_ptr<std::map<std::string, BundleActivePackageStats>> mergedPackageStats =
1029         std::make_shared<std::map<std::string, BundleActivePackageStats>>();
1030     for (auto packageStat : packageStats) {
1031         std::string mergedPackageStatsKey = packageStat.bundleName_ + std::to_string(packageStat.uid_);
1032         auto iter = mergedPackageStats->find(mergedPackageStatsKey);
1033         if (iter != mergedPackageStats->end()) {
1034             MergeSamePackageStats(iter->second, packageStat);
1035         } else {
1036             mergedPackageStats->
1037                 insert(std::pair<std::string, BundleActivePackageStats>(mergedPackageStatsKey, packageStat));
1038         }
1039     }
1040     for (auto pair : *mergedPackageStats) {
1041         tempPackageStats.push_back(pair.second);
1042     }
1043     return tempPackageStats;
1044 }
1045 // LCOV_EXCL_STOP
MergeSamePackageStats(BundleActivePackageStats & left,const BundleActivePackageStats & right)1046 void BundleActiveService::MergeSamePackageStats(BundleActivePackageStats& left, const BundleActivePackageStats& right)
1047 {
1048     if (left.bundleName_ != right.bundleName_) {
1049         BUNDLE_ACTIVE_LOGE("Merge package stats failed, existing packageName : %{public}s,"
1050             " new packageName : %{public}s,", left.bundleName_.c_str(), right.bundleName_.c_str());
1051         return;
1052     }
1053     left.lastTimeUsed_ = std::max(left.lastTimeUsed_, right.lastTimeUsed_);
1054     left.lastContiniousTaskUsed_ = std::max(left.lastContiniousTaskUsed_, right.lastContiniousTaskUsed_);
1055     left.totalInFrontTime_ += right.totalInFrontTime_;
1056     left.totalContiniousTaskUsedTime_ += right.totalContiniousTaskUsedTime_;
1057     left.bundleStartedCount_ += right.bundleStartedCount_;
1058 }
1059 }  // namespace DeviceUsageStats
1060 }  // namespace OHOS
1061 
1062