1 /*
2 * Copyright (c) 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 "wukong_util.h"
17
18 #include <climits>
19 #include <dirent.h>
20 #include <fstream>
21 #include <iostream>
22 #include <memory.h>
23 #include <sstream>
24 #include <sys/stat.h>
25
26 #include "ability_manager_client.h"
27 #include "display_manager.h"
28 #include "if_system_ability_manager.h"
29 #include "iservice_registry.h"
30 #include "launcher_service.h"
31 #include "png.h"
32 #include "string_ex.h"
33 #include "system_ability_definition.h"
34 #include "wukong_define.h"
35 #include "bundle_mgr_proxy.h"
36 #include "common.h"
37 #include "accessibility_ui_test_ability.h"
38 #include "component_manager.h"
39 #include "dump_usage.h"
40
41 namespace OHOS {
42 namespace WuKong {
43 namespace {
44 const std::string DEFAULT_DIR = "/data/local/tmp/wukong/report/";
45 const uint32_t LAP_HEIGHT = 200;
46 const uint32_t CHARGE_STRIDE = 11;
47 const uint32_t BLANK_THR = 30;
48 const uint32_t WHITE_THR = 225;
49 int g_bwCount = 0;
g_isBwScreen(std::shared_ptr<Media::PixelMap> pixelMap)50 bool g_isBwScreen(std::shared_ptr<Media::PixelMap> pixelMap)
51 {
52 auto width = static_cast<uint32_t>(pixelMap->GetWidth());
53 auto height = static_cast<uint32_t>(pixelMap->GetHeight());
54 auto data = pixelMap->GetPixels();
55 auto stride = static_cast<uint32_t>(pixelMap->GetRowBytes());
56 bool isUpper = true;
57 bool isLower = true;
58 uint32_t heightLimit = height - LAP_HEIGHT;
59 for (uint32_t i = LAP_HEIGHT; i < heightLimit && (isUpper || isLower); i += CHARGE_STRIDE) {
60 for (uint32_t j = 0; j < width; j += 1) {
61 auto pixel = *(data + (i * stride) + (j * 4));
62 if (pixel >= BLANK_THR) {
63 isLower = false;
64 }
65 if (pixel <= WHITE_THR) {
66 isUpper = false;
67 }
68 if (!isLower && !isUpper) {
69 break;
70 }
71 }
72 }
73 return isLower || isUpper;
74 }
75
TakeWuKongScreenCap(const std::string & wkScreenPath,const bool checkBWScreen=false)76 bool TakeWuKongScreenCap(const std::string &wkScreenPath, const bool checkBWScreen = false)
77 {
78 // get PixelMap from DisplayManager API
79 Rosen::DisplayManager &displayMgr = Rosen::DisplayManager::GetInstance();
80 std::shared_ptr<Media::PixelMap> pixelMap = displayMgr.GetScreenshot(displayMgr.GetDefaultDisplayId());
81 static constexpr int bitmapDepth = 8;
82 if (pixelMap == nullptr) {
83 DEBUG_LOG("Failed to get display pixelMap");
84 return false;
85 }
86 auto width = static_cast<uint32_t>(pixelMap->GetWidth());
87 auto height = static_cast<uint32_t>(pixelMap->GetHeight());
88 auto data = pixelMap->GetPixels();
89 auto stride = static_cast<uint32_t>(pixelMap->GetRowBytes());
90 if (checkBWScreen) {
91 bool result = g_isBwScreen(pixelMap);
92 if (result) {
93 g_bwCount++;
94 INFO_LOG_STR("isBWScreen is true, BWScreen count : %d", g_bwCount);
95 }
96 }
97 png_structp pngStruct = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
98 if (pngStruct == nullptr) {
99 DEBUG_LOG("error: png_create_write_struct nullptr!");
100 return false;
101 }
102 png_infop pngInfo = png_create_info_struct(pngStruct);
103 if (pngInfo == nullptr) {
104 DEBUG_LOG("error: png_create_info_struct error nullptr!");
105 png_destroy_write_struct(&pngStruct, nullptr);
106 return false;
107 }
108 FILE *fp = fopen(wkScreenPath.c_str(), "wb");
109 if (fp == nullptr) {
110 ERROR_LOG("error: open file error!");
111 png_destroy_write_struct(&pngStruct, &pngInfo);
112 return false;
113 }
114 png_init_io(pngStruct, fp);
115 png_set_IHDR(pngStruct, pngInfo, width, height, bitmapDepth, PNG_COLOR_TYPE_RGBA, PNG_INTERLACE_NONE,
116 PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
117 png_set_packing(pngStruct); // set packing info
118 png_write_info(pngStruct, pngInfo); // write to header
119 for (uint32_t i = 0; i < height; i++) {
120 png_write_row(pngStruct, data + (i * stride));
121 }
122 png_write_end(pngStruct, pngInfo);
123 // free
124 png_destroy_write_struct(&pngStruct, &pngInfo);
125 (void)fclose(fp);
126 return true;
127 }
128 } // namespace
129 using namespace std;
130 using namespace OHOS::AppExecFwk;
131 const int USE_ID = 100;
WuKongUtil()132 WuKongUtil::WuKongUtil()
133 {
134 TRACK_LOG_STD();
135 const int timeBufsize = 32;
136 char fileNameBuf[timeBufsize] = {0};
137 time_t currentTime = time(0);
138 uint32_t res = 0;
139
140 if (currentTime > 0) {
141 tm *timePtr = localtime(¤tTime);
142 if (timePtr == nullptr) {
143 ERROR_LOG("timePtr is nullptr");
144 return;
145 }
146 res = strftime(fileNameBuf, timeBufsize, "%Y%m%d_%H%M%S", timePtr);
147 }
148 if (res > 0) {
149 startRunTime_ = std::string(fileNameBuf);
150 } else {
151 startRunTime_ = "unvalid_time";
152 }
153 curDir_ = DEFAULT_DIR + startRunTime_ + "/";
154 DEBUG_LOG_STR("common dir{%s}", curDir_.c_str());
155 DIR *rootDir = nullptr;
156 std::string dirStr = "/";
157 std::vector<std::string> strs;
158 OHOS::SplitStr(curDir_, "/", strs);
159 for (auto str : strs) {
160 dirStr.append(str);
161 dirStr.append("/");
162 if ((rootDir = opendir(dirStr.c_str())) == nullptr) {
163 int ret = mkdir(dirStr.c_str(), S_IROTH | S_IRWXU | S_IRWXG);
164 if (ret != 0 && dirStr != "/data/" && dirStr != "/data/local/") {
165 std::cerr << "failed to create dir: " << dirStr << std::endl;
166 break;
167 }
168 } else {
169 closedir(rootDir);
170 }
171 }
172 DEBUG_LOG_STR("%s", startRunTime_.c_str());
173 TRACK_LOG_END();
174 }
175
176 /**
177 * @brief: release util
178 */
~WuKongUtil()179 WuKongUtil::~WuKongUtil()
180 {
181 TRACK_LOG_STD();
182 }
183
GetAllAppInfo()184 ErrCode WuKongUtil::GetAllAppInfo()
185 {
186 AppExecFwk::LauncherService launcherservice;
187 std::vector<AppExecFwk::LauncherAbilityInfo> launcherAbilityInfos(0);
188
189 bool result = launcherservice.GetAllLauncherAbilityInfos(USE_ID, launcherAbilityInfos);
190 DEBUG_LOG_STR("GetAllLauncherAbilityInfos: size (%u), result (%d)", launcherAbilityInfos.size(), result);
191 if (launcherAbilityInfos.size() == 0) {
192 ERROR_LOG("GetAllLauncherAbilityInfos size is 0");
193 return OHOS::ERR_INVALID_VALUE;
194 }
195 for (auto item : launcherAbilityInfos) {
196 iconPath_ = item.applicationInfo.iconPath;
197 DEBUG_LOG_STR("iconPath: %s", item.applicationInfo.iconPath.c_str());
198 DEBUG_LOG_STR("codePath: %s", item.applicationInfo.codePath.c_str());
199 DEBUG_LOG_STR("dataDir: %s", item.applicationInfo.dataDir.c_str());
200 DEBUG_LOG_STR("dataBaseDir: %s", item.applicationInfo.dataBaseDir.c_str());
201 DEBUG_LOG_STR("cacheDir: %s", item.applicationInfo.cacheDir.c_str());
202 DEBUG_LOG_STR("entryDir: %s", item.applicationInfo.entryDir.c_str());
203 std::string bundleName = item.elementName.GetBundleName();
204 // store the list of all bundle names
205 bundleList_.push_back(bundleName);
206 abilityList_.push_back(item.elementName.GetAbilityName());
207 uint32_t isInBlockList = FindElement(blockList_, bundleName);
208 if (isInBlockList != INVALIDVALUE) {
209 continue;
210 }
211 // store the list of bundle names except for block list
212 validBundleList_.push_back(bundleName);
213 validAbilityList_.push_back(item.elementName.GetAbilityName());
214 }
215 GetAllAbilities();
216 return OHOS::ERR_OK;
217 }
218
GetBundleList(std::vector<std::string> & bundlelist,std::vector<std::string> & abilitylist)219 void WuKongUtil::GetBundleList(std::vector<std::string> &bundlelist, std::vector<std::string> &abilitylist)
220 {
221 if (bundleList_.size() == 0) {
222 GetAllAppInfo();
223 }
224 bundlelist = bundleList_;
225 abilitylist = abilityList_;
226 }
227
FindElement(std::vector<std::string> & bundleList,std::string key)228 uint32_t WuKongUtil::FindElement(std::vector<std::string> &bundleList, std::string key)
229 {
230 auto it = find(bundleList.begin(), bundleList.end(), key);
231 if (it != bundleList.end()) {
232 return distance(bundleList.begin(), it);
233 }
234 return INVALIDVALUE;
235 }
236
ContainsElement(std::vector<std::string> & bundleList,std::string key)237 bool WuKongUtil::ContainsElement(std::vector<std::string> &bundleList, std::string key)
238 {
239 return INVALIDVALUE != FindElement(bundleList, key);
240 }
241
CheckBundleNameList()242 ErrCode WuKongUtil::CheckBundleNameList()
243 {
244 std::set<std::string> m(allowList_.begin(), allowList_.end());
245
246 for (auto it = blockList_.begin(); it != blockList_.end(); it++) {
247 if (m.find(*it) != m.end()) {
248 ERROR_LOG("invalid param:please check params of '-p' and '-b'");
249 return OHOS::ERR_INVALID_VALUE;
250 }
251 }
252 return OHOS::ERR_OK;
253 }
254
CheckArgumentList(std::vector<std::string> & arguments,bool isAddToList)255 ErrCode WuKongUtil::CheckArgumentList(std::vector<std::string> &arguments, bool isAddToList)
256 {
257 ErrCode result = OHOS::ERR_OK;
258 GetAllAppInfo();
259 for (uint32_t i = 0; i < arguments.size(); i++) {
260 uint32_t index = FindElement(bundleList_, arguments[i]);
261 if (index == INVALIDVALUE) {
262 uint32_t unLaunchedIndex = FindElement(unLaunchedBundleList_, arguments[i]);
263 if (unLaunchedIndex == INVALIDVALUE) {
264 ERROR_LOG_STR("bundle name '%s' is not be included in all bundles", arguments[i].c_str());
265 result = OHOS::ERR_INVALID_VALUE;
266 } else if (isAddToList) {
267 bundleList_.push_back(arguments[i]);
268 abilityList_.push_back(unLaunchedAbilityList_[unLaunchedIndex]);
269 }
270 }
271 }
272 return result;
273 }
274
SetAllowList(const std::string & optarg)275 ErrCode WuKongUtil::SetAllowList(const std::string &optarg)
276 {
277 SplitStr(optarg, ",", allowList_);
278 ErrCode result = CheckArgumentList(allowList_, true);
279 if (result == OHOS::ERR_OK) {
280 // delete repeat argument
281 DelRepeatArguments(allowList_);
282 if (allowList_.size() > 0) {
283 result = CheckBundleNameList();
284 }
285 }
286 return result;
287 }
288
CheckAbilityArgumentList(std::vector<std::string> & arguments)289 ErrCode WuKongUtil::CheckAbilityArgumentList(std::vector<std::string> &arguments)
290 {
291 ErrCode result = OHOS::ERR_OK;
292 GetAllAppInfo();
293 for (uint32_t i = 0; i < arguments.size(); i++) {
294 uint32_t index = FindElement(allAbilityList_, arguments[i]);
295 if (index == INVALIDVALUE) {
296 ERROR_LOG_STR("Ability name '%s' is not be included in all abilities", arguments[i].c_str());
297 result = OHOS::ERR_INVALID_VALUE;
298 }
299 }
300 return result;
301 }
302
SetAllowAbilityList(const std::string & optarg)303 ErrCode WuKongUtil::SetAllowAbilityList(const std::string &optarg)
304 {
305 SplitStr(optarg, ",", allowAbilityList_);
306 ErrCode result = CheckAbilityArgumentList(allowAbilityList_);
307 if (result == OHOS::ERR_OK) {
308 // delete repeat argument
309 DelRepeatArguments(allowAbilityList_);
310 if (allowAbilityList_.size() > 0) {
311 result = CheckAbilityNameList();
312 }
313 }
314 return result;
315 }
316
SetBlockAbilityList(const std::string & optarg)317 ErrCode WuKongUtil::SetBlockAbilityList(const std::string &optarg)
318 {
319 SplitStr(optarg, ",", blockAbilityList_);
320 ErrCode result = CheckAbilityArgumentList(blockAbilityList_);
321 if (result == OHOS::ERR_OK) {
322 // delete repeat argument
323 DelRepeatArguments(blockAbilityList_);
324 if (blockAbilityList_.size() > 0) {
325 result = CheckAbilityNameList();
326 }
327 }
328 return result;
329 }
330
CheckAbilityNameList()331 ErrCode WuKongUtil::CheckAbilityNameList()
332 {
333 std::set<std::string> m(allowAbilityList_.begin(), allowAbilityList_.end());
334
335 for (auto it = blockAbilityList_.begin(); it != blockAbilityList_.end(); it++) {
336 if (m.find(*it) != m.end()) {
337 ERROR_LOG("invalid param:please check params of '-e' and '-E'");
338 return OHOS::ERR_INVALID_VALUE;
339 }
340 }
341 return OHOS::ERR_OK;
342 }
343
SetBlockList(const std::string & optarg)344 ErrCode WuKongUtil::SetBlockList(const std::string &optarg)
345 {
346 SplitStr(optarg, ",", blockList_);
347 ErrCode result = CheckArgumentList(blockList_, false);
348 if (result == OHOS::ERR_OK) {
349 // delete repeat argument
350 DelRepeatArguments(blockList_);
351 if (blockList_.size() > 0) {
352 result = CheckBundleNameList();
353 }
354 }
355 return result;
356 }
357
SetBlockPageList(const std::string & optarg)358 ErrCode WuKongUtil::SetBlockPageList(const std::string &optarg)
359 {
360 ErrCode result = OHOS::ERR_OK;
361 std::vector<std::string> temp;
362 SplitStr(optarg, ",", temp);
363 blockPageList_.insert(blockPageList_.end(), temp.begin(), temp.end());
364 // delete repeat argument
365 DelRepeatArguments(blockPageList_);
366 if (blockPageList_.size() > 0) {
367 stringstream ss;
368 for (const auto& str:blockPageList_) {
369 ss << str << " ";
370 }
371 INFO_LOG_STR("Please confirm that the blocked page is %s", ss.str().c_str());
372 result = OHOS::ERR_OK;
373 }
374 return result;
375 }
376
SetComponentUri(const std::string & optarg)377 ErrCode WuKongUtil::SetComponentUri(const std::string &optarg)
378 {
379 uri_ = optarg;
380 ErrCode result;
381 if (!uri_.empty()) {
382 result = OHOS::ERR_OK;
383 INFO_LOG_STR("Set component Uri is %s", uri_.c_str());
384 } else {
385 result = OHOS::ERR_INVALID_VALUE;
386 ERROR_LOG("Set component Uri is failed, please check -U param");
387 }
388 return result;
389 }
390
SetComponentUriType(const std::string & optarg)391 ErrCode WuKongUtil::SetComponentUriType(const std::string &optarg)
392 {
393 uriType_ = optarg;
394 ErrCode result;
395 if (!uriType_.empty()) {
396 result = OHOS::ERR_OK;
397 INFO_LOG_STR("Set component Uri Type is %s", uriType_.c_str());
398 } else {
399 result = OHOS::ERR_INVALID_VALUE;
400 ERROR_LOG("Set component Uri Type is failed, please check -x param");
401 }
402 return result;
403 }
404
GetComponentUri()405 std::string WuKongUtil::GetComponentUri()
406 {
407 return uri_;
408 }
409
GetComponentUriType()410 std::string WuKongUtil::GetComponentUriType()
411 {
412 return uriType_;
413 }
414
DelRepeatArguments(std::vector<std::string> & argumentlist)415 void WuKongUtil::DelRepeatArguments(std::vector<std::string> &argumentlist)
416 {
417 std::set<std::string> s(argumentlist.begin(), argumentlist.end());
418 argumentlist.assign(s.begin(), s.end());
419 }
420
GetAllowList(std::vector<std::string> & allowList)421 void WuKongUtil::GetAllowList(std::vector<std::string> &allowList)
422 {
423 allowList = allowList_;
424 }
425
GetAllowAbilityList(std::vector<std::string> & allowAbilityList)426 void WuKongUtil::GetAllowAbilityList(std::vector<std::string> &allowAbilityList)
427 {
428 allowAbilityList = allowAbilityList_;
429 }
430
GetBlockList(std::vector<std::string> & blockList)431 void WuKongUtil::GetBlockList(std::vector<std::string> &blockList)
432 {
433 blockList = blockList_;
434 }
435
GetBlockAbilityList(std::vector<std::string> & blockAbilityList)436 void WuKongUtil::GetBlockAbilityList(std::vector<std::string> &blockAbilityList)
437 {
438 blockAbilityList = blockAbilityList_;
439 }
440
GetBlockPageList(std::vector<std::string> & blockPageList)441 void WuKongUtil::GetBlockPageList(std::vector<std::string> &blockPageList)
442 {
443 blockPageList = blockPageList_;
444 }
445
GetValidBundleList(std::vector<std::string> & validbundlelist)446 void WuKongUtil::GetValidBundleList(std::vector<std::string> &validbundlelist)
447 {
448 validbundlelist = validBundleList_;
449 }
450
SetAllAppInfo(std::vector<std::string> & bundleList,std::vector<std::string> & abilityList)451 void WuKongUtil::SetAllAppInfo(std::vector<std::string> &bundleList, std::vector<std::string> &abilityList)
452 {
453 bundleList_ = bundleList;
454 abilityList_ = abilityList;
455 }
456
SetTempAllowList(std::vector<std::string> tempAllowList)457 void WuKongUtil::SetTempAllowList(std::vector<std::string> tempAllowList)
458 {
459 tempAllowList_ = tempAllowList;
460 }
461
GetTempAllowList()462 std::vector<std::string> WuKongUtil::GetTempAllowList()
463 {
464 return tempAllowList_;
465 }
466
SetOrderFlag(bool orderFlag)467 void WuKongUtil::SetOrderFlag(bool orderFlag)
468 {
469 orderFlag_ = orderFlag;
470 }
471
GetOrderFlag()472 bool WuKongUtil::GetOrderFlag()
473 {
474 return orderFlag_;
475 }
476
GetScreenSize(int32_t & width,int32_t & height)477 ErrCode WuKongUtil::GetScreenSize(int32_t &width, int32_t &height)
478 {
479 ErrCode result = OHOS::ERR_OK;
480 if (screenWidth_ == -1 || screenHeight_ == -1) {
481 OHOS::Rosen::DisplayManager &displayMgr = OHOS::Rosen::DisplayManager::GetInstance();
482 sptr<OHOS::Rosen::Display> display = displayMgr.GetDefaultDisplay();
483 if (display == nullptr) {
484 ERROR_LOG("get screen size failed");
485 return OHOS::ERR_NO_INIT;
486 }
487 screenWidth_ = display->GetWidth();
488 screenHeight_ = display->GetHeight();
489 }
490 width = screenWidth_;
491 height = screenHeight_;
492 return result;
493 }
494
GetIconPath(std::string & iconpath)495 void WuKongUtil::GetIconPath(std::string &iconpath)
496 {
497 iconpath = iconPath_;
498 }
499
WukongScreenCap(std::string & screenStorePath,bool gCommandUitest,bool g_commandCHECKBWSCREEN)500 ErrCode WuKongUtil::WukongScreenCap(std::string &screenStorePath, bool gCommandUitest, bool g_commandCHECKBWSCREEN)
501 {
502 using namespace std::chrono;
503 ErrCode result = ERR_OK;
504 auto wukongts = to_string(time_point_cast<milliseconds>(system_clock::now()).time_since_epoch().count());
505 int fileExist_ = access((curDir_ + "screenshot").c_str(), F_OK);
506 if (fileExist_ == 0) {
507 DEBUG_LOG("File exist.");
508 } else {
509 const int wukongScreenShot = mkdir((curDir_ + "screenshot").c_str(), 0777);
510 DEBUG_LOG("File create.");
511 if (wukongScreenShot == -1) {
512 DEBUG_LOG("Error creating directory!");
513 result = ERR_NO_INIT;
514 }
515 }
516 auto wkScreenPath = curDir_ + "screenshot/" + "/" + wukongts + ".png";
517 DEBUG_LOG_STR("WukongScreenCap store path is {%s}", wkScreenPath.c_str());
518 if (gCommandUitest) {
519 auto cm = ComponentManager::GetInstance();
520 auto auita = Accessibility::AccessibilityUITestAbility::GetInstance();
521 auita->Disconnect();
522 std::string uitestCmd = "uitest dumpLayout -i -p " + curDir_ + "screenshot" + "/" + wukongts + ".json";
523 std::string res = Common::runProcess(uitestCmd);
524 DEBUG_LOG_STR("unitestCmd : %s", res.c_str());
525 cm->Disconnect();
526 if (!cm->Connect()) {
527 ERROR_LOG("ComponentManager Connect failed");
528 return OHOS::ERR_INVALID_OPERATION;
529 }
530 }
531 bool isTakeScreen = TakeWuKongScreenCap(wkScreenPath, g_commandCHECKBWSCREEN);
532 if (isTakeScreen == true) {
533 screenStorePath = wkScreenPath;
534 DEBUG_LOG("The snapshot has been created.");
535 } else {
536 DEBUG_LOG("This snapshot can not be created.");
537 }
538 return result;
539 }
540
GetBundleMgrProxy() const541 sptr<IBundleMgr> WuKongUtil::GetBundleMgrProxy() const
542 {
543 sptr<ISystemAbilityManager> systemAbilityManager =
544 SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
545 if (!systemAbilityManager) {
546 ERROR_LOG("failed to get system ability mgr.");
547 return nullptr;
548 }
549
550 sptr<IRemoteObject> remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
551 if (!remoteObject) {
552 ERROR_LOG("failed to get bundle manager proxy.");
553 return nullptr;
554 }
555
556 return iface_cast<IBundleMgr>(remoteObject);
557 }
558
GetAllAbilitiesByBundleName(std::string bundleName,std::vector<std::string> & abilities)559 void WuKongUtil::GetAllAbilitiesByBundleName(std::string bundleName, std::vector<std::string> &abilities)
560 {
561 TRACK_LOG_STD();
562 sptr<IBundleMgr> bundleMgrProxy = GetBundleMgrProxy();
563 std::vector<BundleInfo> bundleInfos;
564 if (!bundleMgrProxy) {
565 ERROR_LOG("bundleMgrProxy is nullptr");
566 return;
567 }
568 bool getInfoResult = bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, USE_ID);
569 if (!getInfoResult) {
570 ERROR_LOG("GetBundleInfos ERR");
571 return;
572 }
573 DEBUG_LOG_STR("bundles length{%d}", bundleInfos.size());
574 for (const auto &bundleIter : bundleInfos) {
575 TRACK_LOG_STR("bundleIter.name{%s}", bundleIter.name.c_str());
576 BundleInfo bundleInfo;
577 if (bundleIter.name == bundleName) {
578 TRACK_LOG_STR("map bundleName{%s}", bundleIter.name.c_str());
579 bool result =
580 bundleMgrProxy->GetBundleInfo(bundleIter.name, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, 100);
581 if (!result) {
582 ERROR_LOG_STR("WriteBundleInfo getBundleInfo result %d, bundleName: %s", result,
583 bundleIter.name.c_str());
584 break;
585 }
586 for (auto &abilityIter : bundleInfo.abilityInfos) {
587 TRACK_LOG_STR("bundleName{%s} container abilities item{%s}", bundleIter.name.c_str(),
588 (abilityIter.name).c_str());
589 abilities.push_back(abilityIter.name);
590 }
591 }
592 }
593 TRACK_LOG_END();
594 }
595
GetAllAbilities()596 ErrCode WuKongUtil::GetAllAbilities()
597 {
598 TRACK_LOG_STD();
599 ErrCode result = OHOS::ERR_INVALID_VALUE;
600 sptr<IBundleMgr> bundleMgrProxy = GetBundleMgrProxy();
601 std::vector<BundleInfo> bundleInfos;
602 if (!bundleMgrProxy) {
603 ERROR_LOG("bundleMgrProxy is nullptr");
604 return result;
605 }
606 bool getInfoResult = bundleMgrProxy->GetBundleInfos(BundleFlag::GET_BUNDLE_DEFAULT, bundleInfos, USE_ID);
607 if (!getInfoResult) {
608 ERROR_LOG("GetBundleInfos ERR");
609 return result;
610 }
611 DEBUG_LOG_STR("bundles length{%d}", bundleInfos.size());
612 for (const auto &bundleIter : bundleInfos) {
613 std::string bundleName = bundleIter.name;
614 uint32_t bundleListIndex = FindElement(bundleList_, bundleName);
615 BundleInfo bundleInfo;
616 bool getBundleResult =
617 bundleMgrProxy->GetBundleInfo(bundleName, BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, 100);
618 if (!getBundleResult) {
619 ERROR_LOG_STR("WriteWuKongBundleInfo getBundleInfo result %d", getBundleResult);
620 continue;
621 }
622 if (bundleListIndex != INVALIDVALUE) {
623 for (auto &abilityIter : bundleInfo.abilityInfos) {
624 allBundleList_.push_back(bundleName);
625 allAbilityList_.push_back(abilityIter.name);
626 DEBUG_LOG_STR("bundleName: %s, abilityName: %s", bundleName.c_str(), abilityIter.name.c_str());
627 }
628 } else {
629 for (auto &abilityIter : bundleInfo.abilityInfos) {
630 unLaunchedBundleList_.push_back(bundleName);
631 unLaunchedAbilityList_.push_back(abilityIter.name);
632 allBundleList_.push_back(bundleName);
633 allAbilityList_.push_back(abilityIter.name);
634 DEBUG_LOG_STR("bundleName: %s, abilityName: %s", bundleName.c_str(), abilityIter.name.c_str());
635 }
636 }
637 }
638 if (unLaunchedAbilityList_.size() > 0) {
639 result = OHOS::ERR_OK;
640 }
641 TRACK_LOG_END();
642 return result;
643 }
644
GetCurrentTestDir()645 std::string WuKongUtil::GetCurrentTestDir()
646 {
647 return curDir_;
648 }
649
CopyFile(std::string & targetFile,std::string & sourceDir,std::string & destDir)650 bool WuKongUtil::CopyFile(std::string &targetFile, std::string &sourceDir, std::string &destDir)
651 {
652 std::ifstream in;
653 std::ofstream out;
654 DEBUG_LOG_STR("targetFile{%s} sourceDir{%s} destDir{%s}", targetFile.c_str(), sourceDir.c_str(), destDir.c_str());
655 char filepathSource[PATH_MAX] = {'\0'};
656 std::string sourceFile = sourceDir + targetFile;
657 char *realPathSource = realpath(sourceFile.c_str(), filepathSource);
658 if (realPathSource == nullptr) {
659 ERROR_LOG_STR("failed to get source file path (%s), errno: (%d)", sourceFile.c_str(), errno);
660 return false;
661 }
662 in.open(filepathSource, std::ios::binary);
663 if (in.fail()) {
664 std::cout << "Error 1: Fail to open the source file." << std::endl;
665 in.close();
666 out.close();
667 return false;
668 }
669
670 char filepathDest[PATH_MAX] = {'\0'};
671 char *realPathDest = realpath(destDir.c_str(), filepathDest);
672 if (realPathDest == nullptr) {
673 ERROR_LOG_STR("failed to get dest dir path (%s), errno: (%d)", destDir.c_str(), errno);
674 return false;
675 }
676 DEBUG_LOG_STR("destDir{%s}", filepathDest);
677 std::string destFile = destDir + targetFile;
678 out.open(destFile.c_str(), std::ios::binary);
679 if (out.fail()) {
680 std::cout << "Error 2: Fail to create the new file." << std::endl;
681 out.close();
682 in.close();
683 return false;
684 }
685 out << in.rdbuf();
686 out.close();
687 in.close();
688 return true;
689 }
690
DeleteFile(std::string targetDir)691 bool WuKongUtil::DeleteFile(std::string targetDir)
692 {
693 DIR *dirdp = nullptr;
694 char filepathSource[PATH_MAX] = {'\0'};
695 char *realPathSource = realpath(targetDir.c_str(), filepathSource);
696 if (realPathSource != nullptr) {
697 struct dirent *dp;
698 dirdp = opendir(targetDir.c_str());
699 while ((dp = readdir(dirdp)) != NULL) {
700 std::string currentFileName(dp->d_name);
701 std::string sourceFile = targetDir + currentFileName;
702 char *realFileSource = realpath(sourceFile.c_str(), filepathSource);
703 if (realFileSource != nullptr) {
704 remove(sourceFile.c_str());
705 }
706 }
707 } else {
708 return false;
709 }
710 (void)closedir(dirdp);
711 return true;
712 }
713
SetCompIdBlockList(const std::string & optarg)714 void WuKongUtil::SetCompIdBlockList(const std::string &optarg)
715 {
716 SplitStr(optarg, ",", compIdBlockList_);
717 }
718
GetCompIdBlockList()719 std::vector<std::string> WuKongUtil::GetCompIdBlockList()
720 {
721 return compIdBlockList_;
722 }
723
SetCompTypeBlockList(const std::string & optarg)724 void WuKongUtil::SetCompTypeBlockList(const std::string &optarg)
725 {
726 SplitStr(optarg, ",", compTypeBlockList_);
727 }
728
GetCompTypeBlockList()729 std::vector<std::string> WuKongUtil::GetCompTypeBlockList()
730 {
731 return compTypeBlockList_;
732 }
733
runProcess(std::string cmd)734 std::string WuKongUtil::runProcess(std::string cmd)
735 {
736 const unsigned int NUMBER_SIZE = 1024;
737 if (FILE* fp = popen(cmd.c_str(), "r")) {
738 std::ostringstream ostrStream;
739 char line[NUMBER_SIZE];
740 while (fgets(line, NUMBER_SIZE, fp)) {
741 ostrStream << line;
742 }
743 pclose(fp);
744 return ostrStream.str();
745 } else {
746 ERROR_LOG("popen function failed");
747 }
748 return "";
749 }
SetIsFirstStartAppFlag(bool isFirstStartApp)750 void WuKongUtil::SetIsFirstStartAppFlag(bool isFirstStartApp)
751 {
752 isFirstStartApp_ = isFirstStartApp;
753 }
GetIsFirstStartAppFlag()754 bool WuKongUtil::GetIsFirstStartAppFlag()
755 {
756 return isFirstStartApp_;
757 }
GetBundlePid()758 std::string WuKongUtil::GetBundlePid()
759 {
760 auto elementName = OHOS::AAFwk::AbilityManagerClient::GetInstance()->GetTopAbility();
761 std::string curBundleName = elementName.GetBundleName();
762 std::string bufCmd = "pidof " + curBundleName;
763 FILE* fp = nullptr;
764 fp = popen(bufCmd.c_str(), "r");
765 TRACK_LOG_STR("Run %s", bufCmd.c_str());
766 if (fp == nullptr) {
767 ERROR_LOG("popen function failed");
768 return "";
769 }
770 const int bufferSize = 32;
771 char pid[bufferSize] = {0};
772 if (fgets(pid, bufferSize - 1, fp) != nullptr) {
773 std::string pidStr(pid);
774 pidStr = OHOS::ReplaceStr(pidStr, "\n", " ");
775 pclose(fp);
776 return pidStr;
777 }
778 pclose(fp);
779 return "";
780 }
781
GetBundlePssTotal()782 uint64_t WuKongUtil::GetBundlePssTotal()
783 {
784 OHOS::HiviewDFX::DumpUsage dumpUsage;
785 std::string pidStr = GetBundlePid();
786 int pid = std::stoi(pidStr);
787 OHOS::HiviewDFX::MemInfoData::MemInfo memInfo;
788 bool success = dumpUsage.GetMemInfo(pid, memInfo);
789 if (success) {
790 uint64_t pss = dumpUsage.GetPss(pid);
791 DEBUG_LOG_STR("Get bundle PssTotal is %d", pss);
792 return pss;
793 }
794 return 0;
795 }
796
797 } // namespace WuKong
798 } // namespace OHOS
799