• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "bundle_test_tool.h"
16 
17 #include <chrono>
18 #include <cstdlib>
19 #include <cstring>
20 #include <future>
21 #include <getopt.h>
22 #include <iostream>
23 #include <set>
24 #include <sstream>
25 #include <thread>
26 #include <unistd.h>
27 #include <vector>
28 
29 #include "app_log_wrapper.h"
30 #include "appexecfwk_errors.h"
31 #include "bundle_command_common.h"
32 #include "bundle_death_recipient.h"
33 #include "bundle_mgr_client.h"
34 #include "bundle_mgr_proxy.h"
35 #include "bundle_tool_callback_stub.h"
36 #include "common_event_manager.h"
37 #include "common_event_support.h"
38 #include "data_group_info.h"
39 #include "directory_ex.h"
40 #include "parameter.h"
41 #include "process_cache_callback_host.h"
42 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
43 #include "quick_fix_status_callback_host_impl.h"
44 #endif
45 #include "status_receiver_impl.h"
46 #include "string_ex.h"
47 #include "json_util.h"
48 
49 namespace OHOS {
50 namespace AppExecFwk {
51 namespace {
52 using OptionHandler = std::function<void(const std::string&)>;
53 
54 const std::string LINE_BREAK = "\n";
55 constexpr int32_t SLEEP_SECONDS = 20;
56 // param
57 const int32_t INDEX_OFFSET = 2;
58 // quick fix error code
59 const int32_t ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED = 801;
60 const int32_t INITIAL_SANDBOX_APP_INDEX = 1000;
61 const int32_t MAX_WAITING_TIME = 600;
62 // quick fix error message
63 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR = "error: quick fix internal error.\n";
64 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR = "error: param error.\n";
65 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED = "error: profile parse failed.\n";
66 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME = "error: not same bundle name.\n";
67 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME = "error: not same version code.\n";
68 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME = "error: not same version name.\n";
69 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME =
70     "error: not same patch version code.\n";
71 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME =
72     "error: not same patch version name.\n";
73 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME = "error: not same patch type.\n";
74 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE = "error: unknown quick fix type.\n";
75 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE = "error: patch so incompatible.\n";
76 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME = "error: same moduleName.\n";
77 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST = "error: bundle name is not existed.\n";
78 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST = "error: module name is not existed.\n";
79 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME = "error: signature is not existed.\n";
80 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED = "error: quick fix add hqf failed.\n";
81 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED =
82     "error: quick fix save innerAppQuickFix failed.\n";
83 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR =
84     "error: quick fix version code require greater than original hqf.\n";
85 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE = "error: no this quick fix info in database.\n";
86 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS = "error: wrong quick fix status.\n";
87 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO =
88     "error: cannot obtain the bundleInfo from data mgr.\n";
89 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED = "error: quick fix remove path failed.\n";
90 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED = "error: extract diff files failed.\n";
91 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED = "error: apply diff patch failed.\n";
92 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN = "error: unknown.\n";
93 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED = "feature is not supported.\n";
94 const std::string MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT = "error: quick fix operation time out.\n";
95 const std::string MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED = "error: bundleMgr service is dead.\n";
96 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE =
97     "error: hotreload not support release bundle.\n";
98 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED = "error: patch type already existed.\n";
99 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED =
100     "error: hotreload type already existed.\n";
101 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO =
102     "error: no patch info in bundleInfo.\n";
103 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED = "error: quick fix move hqf file failed.\n";
104 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED = "error: quick fix create path failed.\n";
105 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB =
106     "error: old patch or hot reload in db.\n";
107 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SEND_REQUEST_FAILED = "error: send request failed.\n";
108 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REAL_PATH_FAILED = "error: obtain realpath failed.\n";
109 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATH = "error: input invalid path.\n";
110 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OPEN_SOURCE_FILE_FAILED = "error: open source file failed.\n";
111 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_FD_FAILED = "error: create file descriptor failed.\n";
112 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_TARGET_DIR = "error: invalid designated target dir\n";
113 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_TARGET_DIR_FAILED = "error: create target dir failed.\n";
114 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PERMISSION_DENIED = "error: quick fix permission denied.\n";
115 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_WRITE_FILE_FAILED = "error: write file to target dir failed.\n";
116 const std::string MSG_ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED =
117     "error: the hqf of release hap cannot contains resources/rawfile.\n";
118 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM =
119     "error: invalid param for setting debug mode.\n";
120 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR =
121     "error: internal error for setting debug mode.\n";
122 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR = "error: parcel error for setting debug mode.\n";
123 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR = "error: send request error.\n";
124 const std::string MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED = "error: uid check failed.\n";
125 
126 static const std::string TOOL_NAME = "bundle_test_tool";
127 static const std::string HELP_MSG =
128     "usage: bundle_test_tool <command> <options>\n"
129     "These are common bundle_test_tool commands list:\n"
130     "  help                             list available commands\n"
131     "  setrm                            set module isRemovable by given bundle name and module name\n"
132     "  getrm                            obtain the value of isRemovable by given bundle name and module name\n"
133     "  installSandbox                   indicates install sandbox\n"
134     "  uninstallSandbox                 indicates uninstall sandbox\n"
135     "  dumpSandbox                      indicates dump sandbox info\n"
136     "  getStr                           obtain the value of label by given bundle name, module name and label id\n"
137     "  getIcon                          obtain the value of icon by given bundle name, module name, "
138     "density and icon id\n"
139     "  addAppInstallRule                obtain the value of install controlRule by given some app id "
140     "control rule type, user id and euid\n"
141     "  getAppInstallRule                obtain the value of install controlRule by given some app id "
142     "rule type, user id and euid\n"
143     "  deleteAppInstallRule             obtain the value of install controlRule by given some app id "
144     "user id and euid\n"
145     "  cleanAppInstallRule              obtain the value of install controlRule by given rule type "
146     "user id and euid\n"
147     "  addAppRunningRule                obtain the value of app running control rule "
148     "by given controlRule user id and euidn\n"
149     "  deleteAppRunningRule             obtain the value of app running control rule "
150     "by given controlRule user id and euid\n"
151     "  cleanAppRunningRule              obtain the value of app running control "
152     "rule by given user id and euid\n"
153     "  getAppRunningControlRule         obtain the value of app running control rule "
154     "by given user id and euid and some app id\n"
155     "  getAppRunningControlRuleResult   obtain the value of app running control rule "
156     "by given bundleName user id, euid and controlRuleResult\n"
157     "  deployQuickFix                   deploy a quick fix patch of an already installed bundle\n"
158     "  switchQuickFix                   switch a quick fix patch of an already installed bundle\n"
159     "  deleteQuickFix                   delete a quick fix patch of an already installed bundle\n"
160     "  setDebugMode                     enable signature debug mode\n"
161     "  getBundleStats                   get bundle stats\n"
162     "  getAppProvisionInfo              get appProvisionInfo\n"
163     "  getDistributedBundleName         get distributedBundleName\n"
164     "  eventCB                          register then unregister bundle event callback\n"
165     "  resetAOTCompileStatus            reset AOTCompileStatus\n"
166     "  sendCommonEvent                  send common event\n"
167     "  queryDataGroupInfos              obtain the data group infos of the application\n"
168     "  getGroupDir                      obtain the data group dir path by data group id\n"
169     "  getJsonProfile                   obtain the json string of the specified module\n"
170     "  getOdid                          obtain the odid of the application\n"
171     "  getUidByBundleName               obtain the uid string of the specified bundle\n"
172     "  implicitQuerySkillUriInfo        obtain the skill uri info of the implicit query ability\n"
173     "  queryAbilityInfoByContinueType   get ability info by continue type\n"
174     "  cleanBundleCacheFilesAutomatic   clear cache data of a specified size\n"
175     "  getContinueBundleName            get continue bundle name list\n"
176     "  getSimpleAppInfoForUid           get bundlename list and appIndex list by uid list\n"
177     "  getAllBundleCacheStat            obtain all bundle cache size \n"
178     "  cleanAllBundleCache                del all bundle cache \n"
179     "  getBundleNameByAppId             get bundlename by appid or appIdentifier\n";
180 
181 const std::string HELP_MSG_GET_REMOVABLE =
182     "usage: bundle_test_tool getrm <options>\n"
183     "eg:bundle_test_tool getrm -m <module-name> -n <bundle-name> \n"
184     "options list:\n"
185     "  -h, --help                             list available commands\n"
186     "  -n, --bundle-name  <bundle-name>       get isRemovable by moduleNmae and bundleName\n"
187     "  -m, --module-name <module-name>        get isRemovable by moduleNmae and bundleName\n";
188 
189 const std::string HELP_MSG_NO_REMOVABLE_OPTION =
190     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
191     "and a module name with '-m' or '--module-name' \n";
192 
193 const std::string HELP_MSG_SET =
194     "usage: bundle_test_tool setrm <options>\n"
195     "eg:bundle_test_tool setrm -m <module-name> -n <bundle-name> -i 1\n"
196     "options list:\n"
197     "  -h, --help                               list available commands\n"
198     "  -n, --bundle-name  <bundle-name>         set isRemovable by moduleNmae and bundleName\n"
199     "  -i, --is-removable <is-removable>        set isRemovable  0 or 1\n"
200     "  -m, --module-name <module-name>          set isRemovable by moduleNmae and bundleName\n";
201 
202 const std::string HELP_MSG_INSTALL_SANDBOX =
203     "usage: bundle_test_tool installSandbox <options>\n"
204     "options list:\n"
205     "  -h, --help                             list available commands\n"
206     "  -u, --user-id <user-id>                specify a user id\n"
207     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n"
208     "  -d, --dlp-type <dlp-type>              specify type of the sandbox application\n";
209 
210 const std::string HELP_MSG_UNINSTALL_SANDBOX =
211     "usage: bundle_test_tool uninstallSandbox <options>\n"
212     "options list:\n"
213     "  -h, --help                             list available commands\n"
214     "  -u, --user-id <user-id>                specify a user id\n"
215     "  -a, --app-index <app-index>            specify a app index\n"
216     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
217 
218 const std::string HELP_MSG_DUMP_SANDBOX =
219     "usage: bundle_test_tool dumpSandbox <options>\n"
220     "options list:\n"
221     "  -h, --help                             list available commands\n"
222     "  -u, --user-id <user-id>                specify a user id\n"
223     "  -a, --app-index <app-index>            specify a app index\n"
224     "  -n, --bundle-name <bundle-name>        install a sandbox of a bundle\n";
225 
226 const std::string HELP_MSG_GET_STRING =
227     "usage: bundle_test_tool getStr <options>\n"
228     "eg:bundle_test_tool getStr -m <module-name> -n <bundle-name> -u <user-id> -i --id <id> \n"
229     "options list:\n"
230     "  -h, --help                             list available commands\n"
231     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
232     "  -m, --module-name <module-name>        specify module name of the application\n"
233     "  -u, --user-id <user-id>                specify a user id\n"
234     "  -i, --id <id>                          specify a label id of the application\n";
235 
236 const std::string HELP_MSG_GET_ICON =
237     "usage: bundle_test_tool getIcon <options>\n"
238     "eg:bundle_test_tool getIcon -m <module-name> -n <bundle-name> -u <user-id> -d --density <density> -i --id <id> \n"
239     "options list:\n"
240     "  -h, --help                             list available commands\n"
241     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
242     "  -m, --module-name <module-name>        specify module name of the application\n"
243     "  -u, --user-id <user-id>                specify a user id\n"
244     "  -d, --density <density>                specify a density\n"
245     "  -i, --id <id>                          specify a icon id of the application\n";
246 
247 const std::string HELP_MSG_NO_GETSTRING_OPTION =
248     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
249     "and a module name with '-m' or '--module-name' \n"
250     "and a userid with '-u' or '--user-id' \n"
251     "and a labelid with '-i' or '--id' \n";
252 
253 const std::string HELP_MSG_NO_GETICON_OPTION =
254     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
255     "and a module name with '-m' or '--module-name' \n"
256     "and a userid with '-u' or '--user-id' \n"
257     "and a density with '-d' or '--density' \n"
258     "and a iconid with '-i' or '--id' \n";
259 
260 const std::string HELP_MSG_ADD_INSTALL_RULE =
261     "usage: bundle_test_tool <options>\n"
262     "eg:bundle_test_tool addAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
263     "options list:\n"
264     "  -h, --help                             list available commands\n"
265     "  -a, --app-id <app-id>                  specify app id of the application\n"
266     "  -e, --euid <eu-id>                     default euid value is 3057\n"
267     "  -t, --control-rule-type                specify control type of the application\n"
268     "  -u, --user-id <user-id>                specify a user id\n";
269 
270 const std::string HELP_MSG_GET_INSTALL_RULE =
271     "usage: bundle_test_tool <options>\n"
272     "eg:bundle_test_tool getAppInstallRule -t <control-rule-type> -u <user-id> \n"
273     "options list:\n"
274     "  -h, --help                             list available commands\n"
275     "  -e, --euid <eu-id>                     default euid value is 3057\n"
276     "  -t, --control-rule-type                specify control type of the application\n"
277     "  -u, --user-id <user-id>                specify a user id\n";
278 
279 const std::string HELP_MSG_DELETE_INSTALL_RULE =
280     "usage: bundle_test_tool <options>\n"
281     "eg:bundle_test_tool deleteAppInstallRule -a <app-id> -t <control-rule-type> -u <user-id> \n"
282     "options list:\n"
283     "  -h, --help                             list available commands\n"
284     "  -e, --euid <eu-id>                     default euid value is 3057\n"
285     "  -a, --app-id <app-id>                  specify app id of the application\n"
286     "  -t, --control-rule-type                specify control type of the application\n"
287     "  -u, --user-id <user-id>                specify a user id\n";
288 
289 const std::string HELP_MSG_CLEAN_INSTALL_RULE =
290     "usage: bundle_test_tool <options>\n"
291     "eg:bundle_test_tool cleanAppInstallRule -t <control-rule-type> -u <user-id> \n"
292     "options list:\n"
293     "  -h, --help                             list available commands\n"
294     "  -e, --euid <eu-id>                     default euid value is 3057\n"
295     "  -t, --control-rule-type                specify control type of the application\n"
296     "  -u, --user-id <user-id>                specify a user id\n";
297 
298 const std::string HELP_MSG_ADD_APP_RUNNING_RULE =
299     "usage: bundle_test_tool <options>\n"
300     "eg:bundle_test_tool addAppRunningRule -c <control-rule> -u <user-id> \n"
301     "options list:\n"
302     "  -h, --help                             list available commands\n"
303     "  -e, --euid <eu-id>                     default euid value is 3057\n"
304     "  -c, --control-rule                     specify control rule of the application\n"
305     "  -u, --user-id <user-id>                specify a user id\n";
306 
307 const std::string HELP_MSG_DELETE_APP_RUNNING_RULE =
308     "usage: bundle_test_tool <options>\n"
309     "eg:bundle_test_tool deleteAppRunningRule -c <control-rule> -u <user-id> \n"
310     "options list:\n"
311     "  -h, --help                             list available commands\n"
312     "  -e, --euid <eu-id>                     default euid value is 3057\n"
313     "  -c, --control-rule                     specify control rule of the application\n"
314     "  -u, --user-id <user-id>                specify a user id\n";
315 
316 const std::string HELP_MSG_CLEAN_APP_RUNNING_RULE =
317     "usage: bundle_test_tool <options>\n"
318     "eg:bundle_test_tool cleanAppRunningRule -u <user-id> \n"
319     "options list:\n"
320     "  -h, --help                             list available commands\n"
321     "  -e, --euid <eu-id>                     default euid value is 3057\n"
322     "  -u, --user-id <user-id>                specify a user id\n";
323 
324 const std::string HELP_MSG_GET_APP_RUNNING_RULE =
325     "usage: bundle_test_tool <options>\n"
326     "eg:bundle_test_tool getAppRunningControlRule -u <user-id> \n"
327     "options list:\n"
328     "  -h, --help                             list available commands\n"
329     "  -e, --euid <eu-id>                     default euid value is 3057\n"
330     "  -u, --user-id <user-id>                specify a user id\n";
331 
332 const std::string HELP_MSG_GET_APP_RUNNING_RESULT_RULE =
333     "usage: bundle_test_tool <options>\n"
334     "eg:bundle_test_tool getAppRunningControlRuleResult -n <bundle-name> \n"
335     "options list:\n"
336     "  -h, --help                             list available commands\n"
337     "  -e, --euid <eu-id>                     default euid value is 3057\n"
338     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
339     "  -u, --user-id <user-id>                specify a user id\n";
340 
341 const std::string HELP_MSG_AUTO_CLEAN_CACHE_RULE =
342     "usage: bundle_test_tool <options>\n"
343     "eg:bundle_test_tool cleanBundleCacheFilesAutomatic -s <cache-size> \n"
344     "options list:\n"
345     "  -h, --help                             list available commands\n"
346     "  -s, --cache-size <cache-size>          specify the cache size that needs to be cleaned\n";
347 
348 const std::string HELP_MSG_NO_ADD_INSTALL_RULE_OPTION =
349     "error: you must specify a app id with '-a' or '--app-id' \n"
350     "and a control type with '-t' or '--control-rule-type' \n"
351     "and a userid with '-u' or '--user-id' \n";
352 
353 const std::string HELP_MSG_NO_GET_INSTALL_RULE_OPTION =
354     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
355     "and a userid with '-u' or '--user-id' \n";
356 
357 const std::string HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION =
358     "error: you must specify a control type with '-a' or '--app-id' \n"
359     "and a userid with '-u' or '--user-id' \n";
360 
361 const std::string HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION =
362     "error: you must specify a control type with '-t' or '--control-rule-type' \n"
363     "and a userid with '-u' or '--user-id' \n";
364 
365 const std::string HELP_MSG_NO_APP_RUNNING_RULE_OPTION =
366     "error: you must specify a app running type with '-c' or '--control-rule' \n"
367     "and a userid with '-u' or '--user-id' \n";
368 
369 const std::string HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION =
370     "error: you must specify a app running type with a userid '-u' or '--user-id \n";
371 
372 const std::string HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION =
373     "error: you must specify a app running type with '-a' or '--app-id' \n"
374     "and a userid with '-u' or '--user-id' \n";
375 
376 const std::string HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION =
377     "error: you must specify a app running type with '-n' or '--bundle-name' \n"
378     "and a userid with '-u' or '--user-id' \n";
379 
380 const std::string HELP_MSG_NO_AUTO_CLEAN_CACHE_OPTION =
381     "error: you must specify a cache size with '-s' or '--cache-size' \n";
382 
383 const std::string HELP_MSG_DEPLOY_QUICK_FIX =
384     "usage: bundle_test_tool deploy quick fix <options>\n"
385     "eg:bundle_test_tool deployQuickFix -p <quickFixPath> \n"
386     "options list:\n"
387     "  -h, --help                             list available commands\n"
388     "  -p, --patch-path  <patch-path>         specify patch path of the patch\n"
389     "  -d, --debug  <debug>                   specify deploy mode, 0 represents release, 1 represents debug\n";
390 
391 const std::string HELP_MSG_SWITCH_QUICK_FIX =
392     "usage: bundle_test_tool switch quick fix <options>\n"
393     "eg:bundle_test_tool switchQuickFix -n <bundle-name> \n"
394     "options list:\n"
395     "  -h, --help                             list available commands\n"
396     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n"
397     "  -e, --enbale  <enable>                 enable a deployed patch of disable an under using patch,\n"
398     "                                         1 represents enable and 0 represents disable\n";
399 
400 const std::string HELP_MSG_DELETE_QUICK_FIX =
401     "usage: bundle_test_tool delete quick fix <options>\n"
402     "eg:bundle_test_tool deleteQuickFix -n <bundle-name> \n"
403     "options list:\n"
404     "  -h, --help                             list available commands\n"
405     "  -n, --bundle-name  <bundle-name>       specify bundleName of the patch\n";
406 
407 const std::string HELP_MSG_SET_DEBUG_MODE =
408     "usage: bundle_test_tool setDebugMode <options>\n"
409     "eg:bundle_test_tool setDebugMode -e <0/1>\n"
410     "options list:\n"
411     "  -h, --help                             list available commands\n"
412     "  -e, --enable  <enable>                 enable signature debug mode, 1 represents enable debug mode and 0\n"
413     "                                         represents disable debug mode\n";
414 
415 const std::string HELP_MSG_GET_BUNDLE_STATS =
416     "usage: bundle_test_tool getBundleStats <options>\n"
417     "eg:bundle_test_tool getBundleStats -n <bundle-name>\n"
418     "options list:\n"
419     "  -h, --help                             list available commands\n"
420     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
421     "  -u, --user-id <user-id>                specify a user id\n"
422     "  -a, --app-index <app-index>            specify a app index\n";
423 
424 
425 const std::string HELP_MSG_GET_APP_PROVISION_INFO =
426     "usage: bundle_test_tool getAppProvisionInfo <options>\n"
427     "eg:bundle_test_tool getAppProvisionInfo -n <bundle-name>\n"
428     "options list:\n"
429     "  -h, --help                             list available commands\n"
430     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
431     "  -u, --user-id <user-id>                specify a user id\n";
432 
433 const std::string HELP_MSG_GET_DISTRIBUTED_BUNDLE_NAME =
434     "usage: bundle_test_tool getDistributedBundleName <options>\n"
435     "eg:bundle_test_tool getDistributedBundleName -n <network-id> -a <access-token-id>\n"
436     "options list:\n"
437     "  -h, --help                                   list available commands\n"
438     "  -n, --network-id  <network-id>               specify networkId of the application\n"
439     "  -a, --access-token-id <access-token-id>      specify a accessTokenId of the application \n";
440 
441 const std::string HELP_MSG_BUNDLE_EVENT_CALLBACK =
442     "usage: bundle_test_tool eventCB <options>\n"
443     "options list:\n"
444     "  -h, --help           list available commands\n"
445     "  -o, --onlyUnregister only call unregister, default will call register then unregister\n"
446     "  -u, --uid            specify a uid, default is foundation uid\n";
447 
448 const std::string HELP_MSG_RESET_AOT_COMPILE_StATUS =
449     "usage: bundle_test_tool resetAOTCompileStatus <options>\n"
450     "options list:\n"
451     "  -h, --help           list available commands\n"
452     "  -b, --bundle-name    specify bundle name\n"
453     "  -m, --module-name    specify module name\n"
454     "  -t, --trigger-mode   specify trigger mode, default is 0\n"
455     "  -u, --uid            specify a uid, default is bundleName's uid\n";
456 
457 const std::string HELP_MSG_GET_PROXY_DATA =
458     "usage: bundle_test_tool getProxyDataInfos <options>\n"
459     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -u <user-id>\n"
460     "options list:\n"
461     "  -h, --help                             list available commands\n"
462     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
463     "  -m, --module-name <module-name>        specify module name of the application\n"
464     "  -u, --user-id <user-id>                specify a user id\n";
465 
466 const std::string HELP_MSG_GET_ALL_PROXY_DATA =
467     "usage: bundle_test_tool getAllProxyDataInfos <options>\n"
468     "eg:bundle_test_tool getProxyDataInfos -u <user-id>\n"
469     "options list:\n"
470     "  -h, --help                             list available commands\n"
471     "  -u, --user-id <user-id>                specify a user id\n";
472 
473 const std::string HELP_MSG_NO_BUNDLE_NAME_OPTION =
474     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
475 
476 const std::string HELP_MSG_NO_NETWORK_ID_OPTION =
477     "error: you must specify a network id with '-n' or '--network-id' \n";
478 
479 const std::string HELP_MSG_NO_ACCESS_TOKEN_ID_OPTION =
480     "error: you must specify a access token id with '-n' or '--access-token-id' \n";
481 
482 const std::string HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE =
483     "usage: bundle_test_tool setExtNameOrMimeTypeToApp <options>\n"
484     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -a <ability-name>\n"
485     "options list:\n"
486     "  -h, --help                             list available commands\n"
487     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
488     "  -m, --module-name <module-name>        specify module name of the application\n"
489     "  -a, --ability-name <ability-name>      specify ability name of the application\n"
490     "  -e, --ext-name <ext-name>              specify the ext-name\n"
491     "  -t, --mime-type <mime-type>            specify the mime-type\n";
492 
493 const std::string HELP_MSG_DEL_EXT_NAME_OR_MIME_TYPE =
494     "usage: bundle_test_tool setExtNameOrMimeTypeToApp <options>\n"
495     "eg:bundle_test_tool getProxyDataInfos -m <module-name> -n <bundle-name> -a <ability-name>\n"
496     "options list:\n"
497     "  -h, --help                             list available commands\n"
498     "  -n, --bundle-name <bundle-name>        specify bundle name of the application\n"
499     "  -m, --module-name <module-name>        specify module name of the application\n"
500     "  -a, --ability-name <ability-name>      specify ability name of the application\n"
501     "  -e, --ext-name <ext-name>              specify the ext-name\n"
502     "  -t, --mime-type <mime-type>            specify the mime-type\n";
503 
504 const std::string HELP_MSG_QUERY_DATA_GROUP_INFOS =
505     "usage: bundle_test_tool queryDataGroupInfos <options>\n"
506     "eg:bundle_test_tool queryDataGroupInfos -n <bundle-name> -u <user-id>\n"
507     "options list:\n"
508     "  -h, --help                             list available commands\n"
509     "  -n, --bundle-name  <bundle-name>       specify bundle name of the application\n"
510     "  -u, --user-id <user-id>                specify a user id\n";
511 
512 const std::string HELP_MSG_GET_GROUP_DIR =
513     "usage: bundle_test_tool getGroupDir <options>\n"
514     "eg:bundle_test_tool getGroupDir -d <data-group-id>\n"
515     "options list:\n"
516     "  -h, --help                             list available commands\n"
517     "  -d, --data-group-id  <data-group-id>       specify bundle name of the application\n";
518 
519 const std::string HELP_MSG_NO_GET_UID_BY_BUNDLENAME =
520     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
521     "and a userId with '-u' or '--user-id' \n"
522     "and a appIndex with '-a' or '--app-index' \n";
523 
524 const std::string HELP_MSG_NO_GET_JSON_PROFILE_OPTION =
525     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
526     "and a module name with '-m' or '--module-name' \n"
527     "and a userId with '-u' or '--user-id' \n"
528     "and a json profile type with '-p' or '--profile-type' \n";
529 
530 const std::string HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION =
531     "error: you must specify a bundle name with '-n' or '--bundle-name' \n";
532 
533 const std::string HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO =
534     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
535     "and a action with '-a' or '--action' \n"
536     "and a entity with '-e' or '--entity' \n";
537 
538 const std::string HELP_MSG_GET_ODID =
539     "usage: bundle_test_tool getOdid <options>\n"
540     "eg:bundle_test_tool getOdid -u <uid>\n"
541     "options list:\n"
542     "  -h, --help               list available commands\n"
543     "  -u, --uid  <uid>         specify uid of the application\n";
544 
545 const std::string HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE =
546     "error: you must specify a bundle name with '-n' or '--bundle-name' \n"
547     "and a continueType with '-c' or '--continue-type' \n"
548     "and a userId with '-u' or '--user-id' \n";
549 
550 const std::string HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID =
551     "usage: bundle_test_tool GetSimpleAppInfoForUid <options>\n"
552     "eg:bundle_test_tool getSimpleAppInfoForUid -u <uid>,<uid>,<uid>...\n"
553     "options list:\n"
554     "  -u, --uid  <uid>         specify uid of the application\n";
555 
556 const std::string HELP_MSG_GET_ALL_BUNDLE_CACHE_STAT =
557     "usage: bundle_test_tool getAllBundleCacheStat <options>\n"
558     "eg:bundle_test_tool getAllBundleCacheStat\n"
559     "options list:\n"
560     "  -h, --help                             list available commands\n"
561     "  -u, --uid <uid>                specify a uid\n";
562 
563 const std::string HELP_MSG_CLEAN_ALL_BUNDLE_CACHE =
564     "usage: bundle_test_tool cleanAllBundleCache <options>\n"
565     "eg:bundle_test_tool cleanAllBundleCache\n"
566     "options list:\n"
567     "  -h, --help                     list available commands\n"
568     "  -u, --uid <uid>                specify a uid\n";
569 
570 const std::string HELP_MSG_GET_BUNDLENAME_BY_APPID =
571     "usage: bundle_test_tool getBundleNameByAppId <options>\n"
572     "eg:bundle_test_tool getBundleNameByAppId -a <app-id>\n"
573     "options list:\n"
574     "  -a, --app-id <app-id>            specify a app index or app identifier\n";
575 
576 const std::string STRING_GET_BUNDLENAME_BY_APPID_OK = "getBundleNameByAppId is ok \n";
577 const std::string STRING_GET_BUNDLENAME_BY_APPID_NG =
578     "error: failed to getBundleNameByAppId \n";
579 
580 const std::string STRING_GET_SIMPLE_APP_INFO_FOR_UID_OK = "getSimpleAppInfoForUid is ok \n";
581 const std::string STRING_GET_SIMPLE_APP_INFO_FOR_UID_NG =
582     "error: failed to getSimpleAppInfoForUid \n";
583 
584 const std::string STRING_SET_REMOVABLE_OK = "set removable is ok \n";
585 const std::string STRING_SET_REMOVABLE_NG = "error: failed to set removable \n";
586 const std::string STRING_GET_REMOVABLE_OK = "get removable is ok \n";
587 const std::string STRING_GET_REMOVABLE_NG = "error: failed to get removable \n";
588 const std::string STRING_REQUIRE_CORRECT_VALUE =
589     "error: option requires a correct value or note that\n"
590     "the difference in expressions between short option and long option. \n";
591 
592 const std::string STRING_INSTALL_SANDBOX_SUCCESSFULLY = "install sandbox app successfully \n";
593 const std::string STRING_INSTALL_SANDBOX_FAILED = "install sandbox app failed \n";
594 
595 const std::string STRING_UNINSTALL_SANDBOX_SUCCESSFULLY = "uninstall sandbox app successfully\n";
596 const std::string STRING_UNINSTALL_SANDBOX_FAILED = "uninstall sandbox app failed\n";
597 
598 const std::string STRING_DUMP_SANDBOX_FAILED = "dump sandbox app info failed\n";
599 
600 const std::string STRING_GET_STRING_NG = "error: failed to get label \n";
601 
602 const std::string STRING_GET_ICON_NG = "error: failed to get icon \n";
603 
604 const std::string STRING_ADD_RULE_NG = "error: failed to add rule \n";
605 const std::string STRING_GET_RULE_NG = "error: failed to get rule \n";
606 const std::string STRING_DELETE_RULE_NG = "error: failed to delete rule \n";
607 
608 const std::string STRING_DEPLOY_QUICK_FIX_OK = "deploy quick fix successfully\n";
609 const std::string STRING_DEPLOY_QUICK_FIX_NG = "deploy quick fix failed\n";
610 const std::string HELP_MSG_NO_QUICK_FIX_PATH_OPTION = "need a quick fix patch path\n";
611 const std::string STRING_SWITCH_QUICK_FIX_OK = "switch quick fix successfully\n";
612 const std::string STRING_SWITCH_QUICK_FIX_NG = "switch quick fix failed\n";
613 const std::string STRING_DELETE_QUICK_FIX_OK = "delete quick fix successfully\n";
614 const std::string STRING_DELETE_QUICK_FIX_NG = "delete quick fix failed\n";
615 
616 const std::string STRING_SET_DEBUG_MODE_OK = "set debug mode successfully\n";
617 const std::string STRING_SET_DEBUG_MODE_NG = "set debug mode failed\n";
618 
619 const std::string STRING_GET_BUNDLE_STATS_OK = "get bundle stats successfully\n";
620 const std::string STRING_GET_BUNDLE_STATS_NG = "get bundle stats failed\n";
621 
622 const std::string STRING_GET_ALL_BUNDLE_CACHE_STAT_OK = "getAllBundleCacheStat successfully\n";
623 const std::string STRING_GET_ALL_BUNDLE_CACHE_STAT_NG = "getAllBundleCacheStat failed\n";
624 
625 const std::string STRING_CLEAN_ALL_BUNDLE_CACHE_OK = "cleanAllBundleCache successfully\n";
626 const std::string STRING_CLEAN_ALL_BUNDLE_CACHE_NG = "cleanAllBundleCache failed\n";
627 
628 const std::string STRING_GET_APP_PROVISION_INFO_OK = "get appProvisionInfo successfully\n";
629 const std::string STRING_GET_APP_PROVISION_INFO_NG = "get appProvisionInfo failed\n";
630 
631 const std::string STRING_QUERY_DATA_GROUP_INFOS_OK = "queryDataGroupInfos successfully\n";
632 const std::string STRING_QUERY_DATA_GROUP_INFOS_NG = "queryDataGroupInfos failed\n";
633 
634 const std::string STRING_GET_GROUP_DIR_OK = "getGroupDir successfully\n";
635 const std::string STRING_GET_GROUP_DIR_NG = "getGroupDir failed\n";
636 
637 const std::string STRING_GET_JSON_PROFILE_NG = "getJsonProfile failed\n";
638 
639 const std::string STRING_GET_UNINSTALLED_BUNDLE_INFO_NG = "getUninstalledBundleInfo failed\n";
640 
641 const std::string STRING_GET_ODID_OK = "getOdid successfully\n";
642 const std::string STRING_GET_ODID_NG = "getOdid failed\n";
643 
644 const std::string STRING_GET_UID_BY_BUNDLENAME_NG = "getUidByBundleName failed\n";
645 
646 const std::string STRING_IMPLICIT_QUERY_SKILL_URI_INFO_NG =
647     "implicitQuerySkillUriInfo failed\n";
648 
649 const std::string STRING_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE_NG =
650     "queryAbilityInfoByContinueType failed\n";
651 
652 const std::string HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION =
653     "error: you must specify a control type with '-n' or '--network-id' \n"
654     "and a accessTokenId with '-a' or '--access-token-id' \n";
655 
656 const std::string GET_DISTRIBUTED_BUNDLE_NAME_COMMAND_NAME = "getDistributedBundleName";
657 
658 const std::string STRING_GET_DISTRIBUTED_BUNDLE_NAME_OK = "get distributedBundleName successfully\n";
659 const std::string STRING_GET_DISTRIBUTED_BUNDLE_NAME_NG = "get distributedBundleName failed\n";
660 
661 const std::string STRING_GET_PROXY_DATA_NG = "get proxyData failed";
662 
663 const std::string GET_BUNDLE_STATS_ARRAY[] = {
664     "app data size: ",
665     "user data size: ",
666     "distributed data size: ",
667     "database size: ",
668     "cache size: "
669 };
670 
671 const std::string GET_RM = "getrm";
672 const std::string SET_RM = "setrm";
673 const std::string INSTALL_SANDBOX = "installSandbox";
674 const std::string UNINSTALL_SANDBOX = "uninstallSandbox";
675 const std::string DUMP_SANDBOX = "dumpSandbox";
676 
677 const std::string SHORT_OPTIONS = "hn:m:a:d:u:i:";
678 const struct option LONG_OPTIONS[] = {
679     {"help", no_argument, nullptr, 'h'},
680     {"bundle-name", required_argument, nullptr, 'n'},
681     {"module-name", required_argument, nullptr, 'm'},
682     {"ability-name", required_argument, nullptr, 'a'},
683     {"device-id", required_argument, nullptr, 'd'},
684     {"user-id", required_argument, nullptr, 'u'},
685     {"is-removable", required_argument, nullptr, 'i'},
686     {nullptr, 0, nullptr, 0},
687 };
688 
689 const std::string SHORT_OPTIONS_GET_BUNDLENAME_BY_APPID = "ha:";
690 const struct option LONG_OPTIONS_GET_BUNDLENAME_BY_APPID[] = {
691     {"help", no_argument, nullptr, 'h'},
692     {"app-id", required_argument, nullptr, 'a'},
693     {nullptr, 0, nullptr, 0},
694 };
695 
696 const std::string SHORT_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID = "hu:";
697 const struct option LONG_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID[] = {
698     {"help", no_argument, nullptr, 'h'},
699     {"uid", required_argument, nullptr, 'u'},
700     {nullptr, 0, nullptr, 0},
701 };
702 
703 const std::string SHORT_OPTIONS_SANDBOX = "hn:d:u:a:";
704 const struct option LONG_OPTIONS_SANDBOX[] = {
705     {"help", no_argument, nullptr, 'h'},
706     {"bundle-name", required_argument, nullptr, 'n'},
707     {"user-id", required_argument, nullptr, 'u'},
708     {"dlp-type", required_argument, nullptr, 'd'},
709     {"app-index", required_argument, nullptr, 'a'},
710     {nullptr, 0, nullptr, 0},
711 };
712 
713 const std::string SHORT_OPTIONS_GET = "hn:m:u:i:d:";
714 const struct option LONG_OPTIONS_GET[] = {
715     {"help", no_argument, nullptr, 'h'},
716     {"bundle-name", required_argument, nullptr, 'n'},
717     {"module-name", required_argument, nullptr, 'm'},
718     {"user-id", required_argument, nullptr, 'u'},
719     {"id", required_argument, nullptr, 'i'},
720     {"density", required_argument, nullptr, 'd'},
721     {nullptr, 0, nullptr, 0},
722 };
723 
724 const std::string SHORT_OPTIONS_RULE = "ha:c:n:e:r:t:u:";
725 const struct option LONG_OPTIONS_RULE[] = {
726     {"help", no_argument, nullptr, 'h'},
727     {"app-id", required_argument, nullptr, 'a'},
728     {"control-rule", required_argument, nullptr, 'c'},
729     {"bundle-name", required_argument, nullptr, 'n'},
730     {"bundle-name", required_argument, nullptr, 'n'},
731     {"euid", required_argument, nullptr, 'e'},
732     {"control-rule-type", required_argument, nullptr, 't'},
733     {"user-id", required_argument, nullptr, 'u'},
734     {nullptr, 0, nullptr, 0},
735 };
736 
737 const std::string SHORT_OPTIONS_AUTO_CLEAN_CACHE = "hs:";
738 const struct option LONG_OPTIONS_AUTO_CLEAN_CACHE[] = {
739     {"help", no_argument, nullptr, 'h'},
740     {"cache-size", required_argument, nullptr, 's'},
741     {nullptr, 0, nullptr, 0},
742 };
743 
744 const std::string SHORT_OPTIONS_QUICK_FIX = "hp:n:e:d:";
745 const struct option LONG_OPTIONS_QUICK_FIX[] = {
746     {"help", no_argument, nullptr, 'h'},
747     {"patch-path", required_argument, nullptr, 'p'},
748     {"bundle-name", required_argument, nullptr, 'n'},
749     {"enable", required_argument, nullptr, 'e'},
750     {"debug", required_argument, nullptr, 'd'},
751     {nullptr, 0, nullptr, 0},
752 };
753 
754 const std::string SHORT_OPTIONS_DEBUG_MODE = "he:";
755 const struct option LONG_OPTIONS_DEBUG_MODE[] = {
756     {"help", no_argument, nullptr, 'h'},
757     {"enable", required_argument, nullptr, 'e'},
758     {nullptr, 0, nullptr, 0},
759 };
760 
761 const std::string SHORT_OPTIONS_GET_BUNDLE_STATS = "hn:u:a:";
762 const struct option LONG_OPTIONS_GET_BUNDLE_STATS[] = {
763     {"help", no_argument, nullptr, 'h'},
764     {"bundle-name", required_argument, nullptr, 'n'},
765     {"user-id", required_argument, nullptr, 'u'},
766     {"app-index", required_argument, nullptr, 'a'},
767     {nullptr, 0, nullptr, 0},
768 };
769 
770 const std::string SHORT_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT = "hu:";
771 const struct option LONG_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT[] = {
772     {"help", no_argument, nullptr, 'h'},
773     {"uid", required_argument, nullptr, 'u'},
774     {nullptr, 0, nullptr, 0},
775 };
776 
777 const std::string SHORT_OPTIONS_CLEAN_ALL_BUNDLE_CACHE = "hu:";
778 const struct option LONG_OPTIONS_CLEAN_ALL_BUNDLE_CACHE[] = {
779     {"help", no_argument, nullptr, 'h'},
780     {"userId", required_argument, nullptr, 'u'},
781     {nullptr, 0, nullptr, 0},
782 };
783 
784 const std::string SHORT_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME = "hn:a:";
785 const struct option LONG_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME[] = {
786     {"help", no_argument, nullptr, 'h'},
787     {"network-id", required_argument, nullptr, 'n'},
788     {"access-token-id", required_argument, nullptr, 'a'},
789     {nullptr, 0, nullptr, 0},
790 };
791 
792 const std::string SHORT_OPTIONS_BUNDLE_EVENT_CALLBACK = "hou:";
793 const struct option LONG_OPTIONS_BUNDLE_EVENT_CALLBACK[] = {
794     {"help", no_argument, nullptr, 'h'},
795     {"onlyUnregister", no_argument, nullptr, 'o'},
796     {"uid", required_argument, nullptr, 'u'},
797     {nullptr, 0, nullptr, 0},
798 };
799 
800 const std::string SHORT_OPTIONS_RESET_AOT_COMPILE_StATUS = "b:m:t:u:";
801 const struct option LONG_OPTIONS_RESET_AOT_COMPILE_StATUS[] = {
802     {"help", no_argument, nullptr, 'h'},
803     {"bundle-name", required_argument, nullptr, 'b'},
804     {"module-name", required_argument, nullptr, 'm'},
805     {"trigger-mode", required_argument, nullptr, 't'},
806     {"uid", required_argument, nullptr, 'u'},
807     {nullptr, 0, nullptr, 0},
808 };
809 
810 const std::string SHORT_OPTIONS_PROXY_DATA = "hn:m:u:";
811 const struct option LONG_OPTIONS_PROXY_DATA[] = {
812     {"help", no_argument, nullptr, 'h'},
813     {"bundle-name", required_argument, nullptr, 'n'},
814     {"module-name", required_argument, nullptr, 'm'},
815     {"user-id", required_argument, nullptr, 'u'},
816     {nullptr, 0, nullptr, 0},
817 };
818 
819 const std::string SHORT_OPTIONS_ALL_PROXY_DATA = "hu:";
820 const struct option LONG_OPTIONS_ALL_PROXY_DATA[] = {
821     {"help", no_argument, nullptr, 'h'},
822     {"user-id", required_argument, nullptr, 'u'},
823     {nullptr, 0, nullptr, 0},
824 };
825 
826 const std::string SHORT_OPTIONS_GET_UID_BY_BUNDLENAME = "hn:u:a:";
827 const struct option LONG_OPTIONS_GET_UID_BY_BUNDLENAME[] = {
828     {"help", no_argument, nullptr, 'h'},
829     {"bundle-name", required_argument, nullptr, 'n'},
830     {"user-id", required_argument, nullptr, 'u'},
831     {"app-index", required_argument, nullptr, 'a'},
832     {nullptr, 0, nullptr, 0},
833 };
834 
835 const std::string SHORT_OPTIONS_MIME = "ha:e:m:n:t:";
836 const struct option LONG_OPTIONS_MIME[] = {
837     {"help", no_argument, nullptr, 'h'},
838     {"ability-name", required_argument, nullptr, 'a'},
839     {"ext-name", required_argument, nullptr, 'e'},
840     {"module-name", required_argument, nullptr, 'm'},
841     {"bundle-name", required_argument, nullptr, 'n'},
842     {"mime-type", required_argument, nullptr, 't'},
843     {nullptr, 0, nullptr, 0},
844 };
845 
846 const std::string SHORT_OPTIONS_GET_GROUP_DIR = "hd:";
847 const struct option LONG_OPTIONS_GET_GROUP_DIR[] = {
848     {"help", no_argument, nullptr, 'h'},
849     {"data-group-id", required_argument, nullptr, 'd'},
850     {nullptr, 0, nullptr, 0},
851 };
852 
853 const std::string SHORT_OPTIONS_GET_JSON_PROFILE = "hp:n:m:u:";
854 const struct option LONG_OPTIONS_GET_JSON_PROFILE[] = {
855     {"help", no_argument, nullptr, 'h'},
856     {"profile-type", required_argument, nullptr, 'p'},
857     {"bundle-name", required_argument, nullptr, 'n'},
858     {"module-name", required_argument, nullptr, 'm'},
859     {"user-id", required_argument, nullptr, 'u'},
860     {nullptr, 0, nullptr, 0},
861 };
862 
863 const std::string SHORT_OPTIONS_UNINSTALLED_BUNDLE_INFO = "hn:";
864 const struct option LONG_OPTIONS_UNINSTALLED_BUNDLE_INFO[] = {
865     {"help", no_argument, nullptr, 'h'},
866     {"bundle-name", required_argument, nullptr, 'n'},
867     {nullptr, 0, nullptr, 0},
868 };
869 
870 const std::string SHORT_OPTIONS_GET_ODID = "hu:";
871 const struct option LONG_OPTIONS_GET_ODID[] = {
872     {"help", no_argument, nullptr, 'h'},
873     {"uid", required_argument, nullptr, 'u'},
874 };
875 
876 const std::string SHORT_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO = "hn:a:e:u:t:";
877 const struct option LONG_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO[] = {
878     {"help", no_argument, nullptr, 'h'},
879     {"bundle-name", required_argument, nullptr, 'n'},
880     {"action", required_argument, nullptr, 'a'},
881     {"entity", required_argument, nullptr, 'e'},
882     {"uri", required_argument, nullptr, 'u'},
883     {"type", required_argument, nullptr, 't'},
884     {nullptr, 0, nullptr, 0},
885 };
886 
887 const std::string SHORT_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE = "hn:c:u:";
888 const struct option LONG_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE[] = {
889     {"help", no_argument, nullptr, 'h'},
890     {"bundle-name", required_argument, nullptr, 'n'},
891     {"continueType", required_argument, nullptr, 'c'},
892     {"userId", required_argument, nullptr, 'u'},
893     {nullptr, 0, nullptr, 0},
894 };
895 }  // namespace
896 
897 class ProcessCacheCallbackImpl : public ProcessCacheCallbackHost {
898 public:
ProcessCacheCallbackImpl()899     ProcessCacheCallbackImpl() {}
~ProcessCacheCallbackImpl()900     ~ProcessCacheCallbackImpl() {}
901     bool WaitForCleanCompletion();
902     bool WaitForStatCompletion();
903     void OnGetAllBundleCacheFinished(uint64_t cacheStat) override;
904     void OnCleanAllBundleCacheFinished(int32_t result) override;
GetCacheStat()905     uint64_t GetCacheStat()
906     {
907         return cacheSize_;
908     }
GetDelRet()909     int32_t GetDelRet()
910     {
911         return cleanRet_;
912     }
913 private:
914     std::mutex mutex_;
915     bool complete_ = false;
916     int32_t cleanRet_ = 0;
917     uint64_t cacheSize_ = 0;
918     std::promise<void> clean_;
919     std::future<void> cleanFuture_ = clean_.get_future();
920     std::promise<void> stat_;
921     std::future<void> statFuture_ = stat_.get_future();
922     DISALLOW_COPY_AND_MOVE(ProcessCacheCallbackImpl);
923 };
924 
OnGetAllBundleCacheFinished(uint64_t cacheStat)925 void ProcessCacheCallbackImpl::OnGetAllBundleCacheFinished(uint64_t cacheStat)
926 {
927     std::lock_guard<std::mutex> lock(mutex_);
928     if (!complete_) {
929         complete_ = true;
930         cacheSize_ = cacheStat;
931         stat_.set_value();
932     }
933 }
934 
OnCleanAllBundleCacheFinished(int32_t result)935 void ProcessCacheCallbackImpl::OnCleanAllBundleCacheFinished(int32_t result)
936 {
937     std::lock_guard<std::mutex> lock(mutex_);
938     if (!complete_) {
939         complete_ = true;
940         cleanRet_ = result;
941         clean_.set_value();
942     }
943 }
944 
WaitForCleanCompletion()945 bool ProcessCacheCallbackImpl::WaitForCleanCompletion()
946 {
947     if (cleanFuture_.wait_for(std::chrono::seconds(MAX_WAITING_TIME)) == std::future_status::ready) {
948         return true;
949     }
950     return false;
951 }
952 
WaitForStatCompletion()953 bool ProcessCacheCallbackImpl::WaitForStatCompletion()
954 {
955     if (statFuture_.wait_for(std::chrono::seconds(MAX_WAITING_TIME)) == std::future_status::ready) {
956         return true;
957     }
958     return false;
959 }
960 
BundleEventCallbackImpl()961 BundleEventCallbackImpl::BundleEventCallbackImpl()
962 {
963     APP_LOGI("create BundleEventCallbackImpl");
964 }
965 
~BundleEventCallbackImpl()966 BundleEventCallbackImpl::~BundleEventCallbackImpl()
967 {
968     APP_LOGI("destroy BundleEventCallbackImpl");
969 }
970 
OnReceiveEvent(const EventFwk::CommonEventData eventData)971 void BundleEventCallbackImpl::OnReceiveEvent(const EventFwk::CommonEventData eventData)
972 {
973     const Want &want = eventData.GetWant();
974     std::string bundleName = want.GetElement().GetBundleName();
975     std::string moduleName = want.GetElement().GetModuleName();
976     APP_LOGI("OnReceiveEvent, bundleName:%{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
977 }
978 
BundleTestTool(int argc,char * argv[])979 BundleTestTool::BundleTestTool(int argc, char *argv[]) : ShellCommand(argc, argv, TOOL_NAME)
980 {}
981 
~BundleTestTool()982 BundleTestTool::~BundleTestTool()
983 {}
984 
CreateCommandMap()985 ErrCode BundleTestTool::CreateCommandMap()
986 {
987     commandMap_ = {
988         {"help", std::bind(&BundleTestTool::RunAsHelpCommand, this)},
989         {"check", std::bind(&BundleTestTool::RunAsCheckCommand, this)},
990         {"setrm", std::bind(&BundleTestTool::RunAsSetRemovableCommand, this)},
991         {"getrm", std::bind(&BundleTestTool::RunAsGetRemovableCommand, this)},
992         {"installSandbox", std::bind(&BundleTestTool::RunAsInstallSandboxCommand, this)},
993         {"uninstallSandbox", std::bind(&BundleTestTool::RunAsUninstallSandboxCommand, this)},
994         {"dumpSandbox", std::bind(&BundleTestTool::RunAsDumpSandboxCommand, this)},
995         {"getStr", std::bind(&BundleTestTool::RunAsGetStringCommand, this)},
996         {"getIcon", std::bind(&BundleTestTool::RunAsGetIconCommand, this)},
997         {"addAppInstallRule", std::bind(&BundleTestTool::RunAsAddInstallRuleCommand, this)},
998         {"getAppInstallRule", std::bind(&BundleTestTool::RunAsGetInstallRuleCommand, this)},
999         {"deleteAppInstallRule", std::bind(&BundleTestTool::RunAsDeleteInstallRuleCommand, this)},
1000         {"cleanAppInstallRule", std::bind(&BundleTestTool::RunAsCleanInstallRuleCommand, this)},
1001         {"addAppRunningRule", std::bind(&BundleTestTool::RunAsAddAppRunningRuleCommand, this)},
1002         {"deleteAppRunningRule", std::bind(&BundleTestTool::RunAsDeleteAppRunningRuleCommand, this)},
1003         {"cleanAppRunningRule", std::bind(&BundleTestTool::RunAsCleanAppRunningRuleCommand, this)},
1004         {"getAppRunningControlRule", std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleCommand, this)},
1005         {"getAppRunningControlRuleResult",
1006             std::bind(&BundleTestTool::RunAsGetAppRunningControlRuleResultCommand, this)},
1007         {"deployQuickFix", std::bind(&BundleTestTool::RunAsDeployQuickFix, this)},
1008         {"switchQuickFix", std::bind(&BundleTestTool::RunAsSwitchQuickFix, this)},
1009         {"deleteQuickFix", std::bind(&BundleTestTool::RunAsDeleteQuickFix, this)},
1010         {"setDebugMode", std::bind(&BundleTestTool::RunAsSetDebugMode, this)},
1011         {"getBundleStats", std::bind(&BundleTestTool::RunAsGetBundleStats, this)},
1012         {"getAllBundleCacheStat", std::bind(&BundleTestTool::RunAsGetAllBundleCacheStat, this)},
1013         {"cleanAllBundleCache", std::bind(&BundleTestTool::RunAsCleanAllBundleCache, this)},
1014         {"getAppProvisionInfo", std::bind(&BundleTestTool::RunAsGetAppProvisionInfo, this)},
1015         {"getDistributedBundleName", std::bind(&BundleTestTool::RunAsGetDistributedBundleName, this)},
1016         {"eventCB", std::bind(&BundleTestTool::HandleBundleEventCallback, this)},
1017         {"resetAOTCompileStatus", std::bind(&BundleTestTool::ResetAOTCompileStatus, this)},
1018         {"sendCommonEvent", std::bind(&BundleTestTool::SendCommonEvent, this)},
1019         {"getProxyDataInfos", std::bind(&BundleTestTool::RunAsGetProxyDataCommand, this)},
1020         {"getAllProxyDataInfos", std::bind(&BundleTestTool::RunAsGetAllProxyDataCommand, this)},
1021         {"setExtNameOrMimeToApp", std::bind(&BundleTestTool::RunAsSetExtNameOrMIMEToAppCommand, this)},
1022         {"delExtNameOrMimeToApp", std::bind(&BundleTestTool::RunAsDelExtNameOrMIMEToAppCommand, this)},
1023         {"queryDataGroupInfos", std::bind(&BundleTestTool::RunAsQueryDataGroupInfos, this)},
1024         {"getGroupDir", std::bind(&BundleTestTool::RunAsGetGroupDir, this)},
1025         {"getJsonProfile", std::bind(&BundleTestTool::RunAsGetJsonProfile, this)},
1026         {"getUninstalledBundleInfo", std::bind(&BundleTestTool::RunAsGetUninstalledBundleInfo, this)},
1027         {"getOdid", std::bind(&BundleTestTool::RunAsGetOdid, this)},
1028         {"getUidByBundleName", std::bind(&BundleTestTool::RunGetUidByBundleName, this)},
1029         {"implicitQuerySkillUriInfo",
1030             std::bind(&BundleTestTool::RunAsImplicitQuerySkillUriInfo, this)},
1031         {"queryAbilityInfoByContinueType",
1032             std::bind(&BundleTestTool::RunAsQueryAbilityInfoByContinueType, this)},
1033         {"cleanBundleCacheFilesAutomatic",
1034             std::bind(&BundleTestTool::RunAsCleanBundleCacheFilesAutomaticCommand, this)},
1035         {"getContinueBundleName",
1036             std::bind(&BundleTestTool::RunAsGetContinueBundleName, this)},
1037         {"getSimpleAppInfoForUid",
1038             std::bind(&BundleTestTool::RunAsGetSimpleAppInfoForUid, this)},
1039         {"getBundleNameByAppId",
1040             std::bind(&BundleTestTool::RunAsGetBundleNameByAppId, this)}
1041     };
1042 
1043     return OHOS::ERR_OK;
1044 }
1045 
CreateMessageMap()1046 ErrCode BundleTestTool::CreateMessageMap()
1047 {
1048     messageMap_ = BundleCommandCommon::bundleMessageMap_;
1049 
1050     return OHOS::ERR_OK;
1051 }
1052 
Init()1053 ErrCode BundleTestTool::Init()
1054 {
1055     APP_LOGI("BundleTestTool Init()");
1056     ErrCode result = OHOS::ERR_OK;
1057     if (bundleMgrProxy_ == nullptr) {
1058         bundleMgrProxy_ = BundleCommandCommon::GetBundleMgrProxy();
1059         if (bundleMgrProxy_ != nullptr) {
1060             if (bundleInstallerProxy_ == nullptr) {
1061                 bundleInstallerProxy_ = bundleMgrProxy_->GetBundleInstaller();
1062             }
1063         }
1064     }
1065 
1066     if ((bundleMgrProxy_ == nullptr) || (bundleInstallerProxy_ == nullptr) ||
1067         (bundleInstallerProxy_->AsObject() == nullptr)) {
1068         result = OHOS::ERR_INVALID_VALUE;
1069     }
1070 
1071 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
1072     if (distributedBmsProxy_ == nullptr) {
1073         distributedBmsProxy_ = BundleCommandCommon::GetDistributedBundleMgrService();
1074     }
1075 #endif
1076 
1077     return result;
1078 }
1079 
CreateQuickFixMsgMap(std::unordered_map<int32_t,std::string> & quickFixMsgMap)1080 void BundleTestTool::CreateQuickFixMsgMap(std::unordered_map<int32_t, std::string> &quickFixMsgMap)
1081 {
1082     quickFixMsgMap = {
1083         { ERR_OK, Constants::EMPTY_STRING },
1084         { ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR },
1085         { ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PARAM_ERROR },
1086         { ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PROFILE_PARSE_FAILED },
1087         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_SAME },
1088         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_NOT_SAME },
1089         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_NAME_NOT_SAME },
1090         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME,
1091             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_CODE_NOT_SAME },
1092         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME,
1093             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_VERSION_NAME_NOT_SAME },
1094         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_TYPE_NOT_SAME },
1095         { ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKNOWN_QUICK_FIX_TYPE },
1096         { ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SO_INCOMPATIBLE },
1097         { ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_BUNDLE_NAME_NOT_EXIST },
1098         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_NOT_EXIST },
1099         { ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME,
1100             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SIGNATURE_INFO_NOT_SAME },
1101         { ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED,
1102             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_EXTRACT_DIFF_FILES_FAILED },
1103         { ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED,
1104             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_APPLY_DIFF_PATCH_FAILED },
1105         { ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_FEATURE_IS_NOT_SUPPORTED },
1106         { ERR_APPEXECFWK_OPERATION_TIME_OUT, MSG_ERR_BUNDLEMANAGER_OPERATION_TIME_OUT },
1107         { ERR_APPEXECFWK_FAILED_SERVICE_DIED, MSG_ERR_BUNDLEMANAGER_FAILED_SERVICE_DIED },
1108         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE,
1109             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_NOT_SUPPORT_RELEASE_BUNDLE },
1110         { ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_PATCH_ALREADY_EXISTED },
1111         { ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED,
1112             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_HOT_RELOAD_ALREADY_EXISTED },
1113         { ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MODULE_NAME_SAME },
1114         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO,
1115             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_INFO_IN_BUNDLE_INFO },
1116         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM },
1117         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR },
1118         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_PARCEL_ERROR },
1119         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR,
1120             MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_SEND_REQUEST_ERROR },
1121         { ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED, MSG_ERR_BUNDLEMANAGER_SET_DEBUG_MODE_UID_CHECK_FAILED },
1122         { ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_ADD_HQF_FAILED },
1123         { ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED,
1124             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_SAVE_APP_QUICK_FIX_FAILED },
1125         { ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_VERSION_CODE_ERROR },
1126         { ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NO_PATCH_IN_DATABASE },
1127         { ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS, MSG_ERR_BUNDLEMANAGER_QUICK_FIX_INVALID_PATCH_STATUS },
1128         { ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO,
1129             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_NOT_EXISTED_BUNDLE_INFO },
1130         { ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED,
1131             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_REMOVE_PATCH_PATH_FAILED },
1132         { ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED,
1133             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_MOVE_PATCH_FILE_FAILED },
1134         { ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED,
1135             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_CREATE_PATCH_PATH_FAILED },
1136         { ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB,
1137             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_OLD_PATCH_OR_HOT_RELOAD_IN_DB },
1138         { ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED,
1139             MSG_ERR_BUNDLEMANAGER_QUICK_FIX_RELEASE_HAP_HAS_RESOURCES_FILE_FAILED }
1140     };
1141 }
1142 
RunAsHelpCommand()1143 ErrCode BundleTestTool::RunAsHelpCommand()
1144 {
1145     resultReceiver_.append(HELP_MSG);
1146 
1147     return OHOS::ERR_OK;
1148 }
1149 
CheckOperation(int userId,std::string deviceId,std::string bundleName,std::string moduleName,std::string abilityName)1150 ErrCode BundleTestTool::CheckOperation(int userId, std::string deviceId, std::string bundleName,
1151     std::string moduleName, std::string abilityName)
1152 {
1153     std::unique_lock<std::mutex> lock(mutex_);
1154     sptr<BundleToolCallbackStub> bundleToolCallbackStub =
1155         new(std::nothrow) BundleToolCallbackStub(cv_, mutex_, dataReady_);
1156     if (bundleToolCallbackStub == nullptr) {
1157         APP_LOGE("bundleToolCallbackStub is null");
1158         return OHOS::ERR_INVALID_VALUE;
1159     }
1160     APP_LOGI("CheckAbilityEnableInstall param: userId:%{public}d, bundleName:%{public}s, moduleName:%{public}s," \
1161         "abilityName:%{public}s", userId, bundleName.c_str(), moduleName.c_str(), abilityName.c_str());
1162     AAFwk::Want want;
1163     want.SetElementName(deviceId, bundleName, abilityName, moduleName);
1164     bool ret = bundleMgrProxy_->CheckAbilityEnableInstall(want, 1, userId, bundleToolCallbackStub);
1165     if (!ret) {
1166         APP_LOGE("CheckAbilityEnableInstall failed");
1167         return OHOS::ERR_OK;
1168     }
1169     APP_LOGI("CheckAbilityEnableInstall wait");
1170     cv_.wait(lock, [this] { return dataReady_; });
1171     dataReady_ = false;
1172     return OHOS::ERR_OK;
1173 }
1174 
RunAsCheckCommand()1175 ErrCode BundleTestTool::RunAsCheckCommand()
1176 {
1177     int counter = 0;
1178     int userId = 100;
1179     std::string deviceId = "";
1180     std::string bundleName = "";
1181     std::string moduleName = "";
1182     std::string abilityName = "";
1183     while (true) {
1184         counter++;
1185         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1186         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1187         if (optind < 0 || optind > argc_) {
1188             return OHOS::ERR_INVALID_VALUE;
1189         }
1190         if (option == -1) {
1191             // When scanning the first argument
1192             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1193                 // 'CheckAbilityEnableInstall' with no option: CheckAbilityEnableInstall
1194                 // 'CheckAbilityEnableInstall' with a wrong argument: CheckAbilityEnableInstall
1195                 APP_LOGD("'CheckAbilityEnableInstall' with no option.");
1196                 return OHOS::ERR_INVALID_VALUE;
1197             }
1198             break;
1199         }
1200         switch (option) {
1201             case 'n': {
1202                 bundleName = optarg;
1203                 break;
1204             }
1205             case 'm': {
1206                 moduleName = optarg;
1207                 break;
1208             }
1209             case 'a': {
1210                 abilityName = optarg;
1211                 break;
1212             }
1213             case 'd': {
1214                 deviceId = optarg;
1215                 break;
1216             }
1217             case 'u': {
1218                 userId = std::stoi(optarg);
1219                 break;
1220             }
1221             default: {
1222                 return OHOS::ERR_INVALID_VALUE;
1223             }
1224         }
1225     }
1226     return CheckOperation(userId, deviceId, bundleName, moduleName, abilityName);
1227 }
1228 
SetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,int isRemovable) const1229 bool BundleTestTool::SetIsRemovableOperation(
1230     const std::string &bundleName, const std::string &moduleName, int isRemovable) const
1231 {
1232     bool enable = true;
1233     if (isRemovable == 0) {
1234         enable = false;
1235     }
1236     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s, enable:%{public}d", bundleName.c_str(), moduleName.c_str(),
1237         enable);
1238     auto ret = bundleMgrProxy_->SetModuleRemovable(bundleName, moduleName, enable);
1239     APP_LOGD("SetModuleRemovable end bundleName: %{public}d", ret);
1240     if (!ret) {
1241         APP_LOGE("SetIsRemovableOperation failed");
1242         return false;
1243     }
1244     return ret;
1245 }
1246 
GetIsRemovableOperation(const std::string & bundleName,const std::string & moduleName,std::string & result) const1247 bool BundleTestTool::GetIsRemovableOperation(
1248     const std::string &bundleName, const std::string &moduleName, std::string &result) const
1249 {
1250     APP_LOGD("bundleName: %{public}s, moduleName:%{public}s", bundleName.c_str(), moduleName.c_str());
1251     bool isRemovable = false;
1252     auto ret = bundleMgrProxy_->IsModuleRemovable(bundleName, moduleName, isRemovable);
1253     APP_LOGD("IsModuleRemovable end bundleName: %{public}s, isRemovable:%{public}d", bundleName.c_str(), isRemovable);
1254     result.append("isRemovable: " + std::to_string(isRemovable) + "\n");
1255     if (ret != ERR_OK) {
1256         APP_LOGE("IsModuleRemovable failed, ret: %{public}d", ret);
1257         return false;
1258     }
1259     return true;
1260 }
1261 
CheckRemovableErrorOption(int option,int counter,const std::string & commandName)1262 bool BundleTestTool::CheckRemovableErrorOption(int option, int counter, const std::string &commandName)
1263 {
1264     if (option == -1) {
1265         if (counter == 1) {
1266             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
1267                 // 'bundle_test_tool setrm/getrm' with no option: bundle_test_tool setrm/getrm
1268                 // 'bundle_test_tool setrm/getrm' with a wrong argument: bundle_test_tool setrm/getrm xxx
1269                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
1270                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
1271                 return false;
1272             }
1273         }
1274         return true;
1275     } else if (option == '?') {
1276         switch (optopt) {
1277             case 'i': {
1278                 if (commandName == GET_RM) {
1279                     std::string unknownOption = "";
1280                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1281                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1282                     resultReceiver_.append(unknownOptionMsg);
1283                 } else {
1284                     APP_LOGD("'bundle_test_tool %{public}s -i' with no argument.", commandName.c_str());
1285                     resultReceiver_.append("error: -i option requires a value.\n");
1286                 }
1287                 break;
1288             }
1289             case 'm': {
1290                 APP_LOGD("'bundle_test_tool %{public}s -m' with no argument.", commandName.c_str());
1291                 resultReceiver_.append("error: -m option requires a value.\n");
1292                 break;
1293             }
1294             case 'n': {
1295                 APP_LOGD("'bundle_test_tool %{public}s -n' with no argument.", commandName.c_str());
1296                 resultReceiver_.append("error: -n option requires a value.\n");
1297                 break;
1298             }
1299             default: {
1300                 std::string unknownOption = "";
1301                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1302                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1303                 resultReceiver_.append(unknownOptionMsg);
1304                 break;
1305             }
1306         }
1307     }
1308     return false;
1309 }
1310 
CheckRemovableCorrectOption(int option,const std::string & commandName,int & isRemovable,std::string & name)1311 bool BundleTestTool::CheckRemovableCorrectOption(
1312     int option, const std::string &commandName, int &isRemovable, std::string &name)
1313 {
1314     bool ret = true;
1315     switch (option) {
1316         case 'h': {
1317             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1318             ret = false;
1319             break;
1320         }
1321         case 'n': {
1322             name = optarg;
1323             APP_LOGD("'bundle_test_tool %{public}s -n %{public}s'", commandName.c_str(), argv_[optind - 1]);
1324             break;
1325         }
1326         case 'i': {
1327             if (commandName == GET_RM) {
1328                 std::string unknownOption = "";
1329                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1330                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1331                 resultReceiver_.append(unknownOptionMsg);
1332                 ret = false;
1333             } else if (OHOS::StrToInt(optarg, isRemovable)) {
1334                 APP_LOGD("'bundle_test_tool %{public}s -i isRemovable:%{public}d, %{public}s'",
1335                     commandName.c_str(), isRemovable, argv_[optind - 1]);
1336             } else {
1337                 APP_LOGE("bundle_test_tool setrm with error %{private}s", optarg);
1338                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1339                 ret = false;
1340             }
1341             break;
1342         }
1343         case 'm': {
1344             name = optarg;
1345             APP_LOGD("'bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s'",
1346                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1347             break;
1348         }
1349         default: {
1350             std::string unknownOption = "";
1351             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1352             APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1353             resultReceiver_.append(unknownOptionMsg);
1354             ret = false;
1355             break;
1356         }
1357     }
1358     return ret;
1359 }
1360 
RunAsSetRemovableCommand()1361 ErrCode BundleTestTool::RunAsSetRemovableCommand()
1362 {
1363     int result = OHOS::ERR_OK;
1364     int counter = 0;
1365     int isRemovable = 0;
1366     std::string commandName = SET_RM;
1367     std::string name = "";
1368     std::string bundleName = "";
1369     std::string moduleName = "";
1370     APP_LOGD("RunAsSetCommand is start");
1371     while (true) {
1372         counter++;
1373         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1374         if (optind < 0 || optind > argc_) {
1375             return OHOS::ERR_INVALID_VALUE;
1376         }
1377         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d, argv_[optind - 1]:%{public}s", option,
1378             optopt, optind, argv_[optind - 1]);
1379         if (option == -1 || option == '?') {
1380             result = !CheckRemovableErrorOption(option, counter, commandName)? OHOS::ERR_INVALID_VALUE : result;
1381             break;
1382         }
1383         result = !CheckRemovableCorrectOption(option, commandName, isRemovable, name)
1384             ? OHOS::ERR_INVALID_VALUE : result;
1385         moduleName = option == 'm' ? name : moduleName;
1386         bundleName = option == 'n' ? name : bundleName;
1387     }
1388     if (result == OHOS::ERR_OK) {
1389         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
1390             APP_LOGD("'bundle_test_tool setrm' with not enough option.");
1391             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
1392             result = OHOS::ERR_INVALID_VALUE;
1393         }
1394     }
1395     if (result != OHOS::ERR_OK) {
1396         resultReceiver_.append(HELP_MSG_SET);
1397     } else {
1398         bool setResult = false;
1399         setResult = SetIsRemovableOperation(bundleName, moduleName, isRemovable);
1400         APP_LOGD("'bundle_test_tool setrm' isRemovable is %{public}d", isRemovable);
1401         resultReceiver_ = setResult ? STRING_SET_REMOVABLE_OK : STRING_SET_REMOVABLE_NG;
1402     }
1403     return result;
1404 }
1405 
RunAsGetRemovableCommand()1406 ErrCode BundleTestTool::RunAsGetRemovableCommand()
1407 {
1408     int result = OHOS::ERR_OK;
1409     int counter = 0;
1410     std::string commandName = GET_RM;
1411     std::string name = "";
1412     std::string bundleName = "";
1413     std::string moduleName = "";
1414     APP_LOGD("RunAsGetRemovableCommand is start");
1415     while (true) {
1416         counter++;
1417         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS.c_str(), LONG_OPTIONS, nullptr);
1418         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1419         if (optind < 0 || optind > argc_) {
1420             return OHOS::ERR_INVALID_VALUE;
1421         }
1422         if (option == -1 || option == '?') {
1423             result = !CheckRemovableErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1424             break;
1425         }
1426         int tempIsRem = 0;
1427         result = !CheckRemovableCorrectOption(option, commandName, tempIsRem, name)
1428             ? OHOS::ERR_INVALID_VALUE : result;
1429         moduleName = option == 'm' ? name : moduleName;
1430         bundleName = option == 'n' ? name : bundleName;
1431     }
1432 
1433     if (result == OHOS::ERR_OK) {
1434         if (resultReceiver_ == "" && (bundleName.size() == 0 || moduleName.size() == 0)) {
1435             APP_LOGD("'bundle_test_tool getrm' with no option.");
1436             resultReceiver_.append(HELP_MSG_NO_REMOVABLE_OPTION);
1437             result = OHOS::ERR_INVALID_VALUE;
1438         }
1439     }
1440 
1441     if (result != OHOS::ERR_OK) {
1442         resultReceiver_.append(HELP_MSG_GET_REMOVABLE);
1443     } else {
1444         std::string results = "";
1445         GetIsRemovableOperation(bundleName, moduleName, results);
1446         if (results.empty()) {
1447             resultReceiver_.append(STRING_GET_REMOVABLE_NG);
1448             return result;
1449         }
1450         resultReceiver_.append(results);
1451     }
1452     return result;
1453 }
1454 
CheckSandboxErrorOption(int option,int counter,const std::string & commandName)1455 bool BundleTestTool::CheckSandboxErrorOption(int option, int counter, const std::string &commandName)
1456 {
1457     if (option == -1) {
1458         if (counter == 1) {
1459             if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
1460                 APP_LOGD("'bundle_test_tool %{public}s' with no option.", commandName.c_str());
1461                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
1462                 return false;
1463             }
1464         }
1465         return true;
1466     } else if (option == '?') {
1467         switch (optopt) {
1468             case 'n':
1469             case 'u':
1470             case 'd':
1471             case 'a': {
1472                 if ((commandName != INSTALL_SANDBOX && optopt == 'd') ||
1473                     (commandName == INSTALL_SANDBOX && optopt == 'a')) {
1474                     std::string unknownOption = "";
1475                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1476                     APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1477                     resultReceiver_.append(unknownOptionMsg);
1478                     break;
1479                 }
1480                 APP_LOGD("'bundle_test_tool %{public}s' -%{public}c with no argument.", commandName.c_str(), optopt);
1481                 resultReceiver_.append("error: option requires a value.\n");
1482                 break;
1483             }
1484             default: {
1485                 std::string unknownOption = "";
1486                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1487                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1488                 resultReceiver_.append(unknownOptionMsg);
1489                 break;
1490             }
1491         }
1492     }
1493     return false;
1494 }
1495 
CheckSandboxCorrectOption(int option,const std::string & commandName,int & data,std::string & bundleName)1496 bool BundleTestTool::CheckSandboxCorrectOption(
1497     int option, const std::string &commandName, int &data, std::string &bundleName)
1498 {
1499     bool ret = true;
1500     switch (option) {
1501         case 'h': {
1502             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1503             ret = false;
1504             break;
1505         }
1506         case 'n': {
1507             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
1508             bundleName = optarg;
1509             break;
1510         }
1511         case 'u':
1512         case 'a':
1513         case 'd': {
1514             if ((commandName != INSTALL_SANDBOX && option == 'd') ||
1515                 (commandName == INSTALL_SANDBOX && option == 'a')) {
1516                 std::string unknownOption = "";
1517                 std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1518                 APP_LOGD("'bundle_test_tool %{public}s' with an unknown option.", commandName.c_str());
1519                 resultReceiver_.append(unknownOptionMsg);
1520                 ret = false;
1521                 break;
1522             }
1523 
1524             APP_LOGD("'bundle_test_tool %{public}s %{public}s %{public}s'", commandName.c_str(),
1525                 argv_[optind - OFFSET_REQUIRED_ARGUMENT], optarg);
1526 
1527             if (!OHOS::StrToInt(optarg, data)) {
1528                 if (option == 'u') {
1529                     APP_LOGE("bundle_test_tool %{public}s with error -u %{private}s", commandName.c_str(), optarg);
1530                 } else if (option == 'a') {
1531                     APP_LOGE("bundle_test_tool %{public}s with error -a %{private}s", commandName.c_str(), optarg);
1532                 } else {
1533                     APP_LOGE("bundle_test_tool %{public}s with error -d %{private}s", commandName.c_str(), optarg);
1534                 }
1535                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
1536                 ret = false;
1537             }
1538             break;
1539         }
1540         default: {
1541             ret = false;
1542             break;
1543         }
1544     }
1545     return ret;
1546 }
1547 
InstallSandboxOperation(const std::string & bundleName,const int32_t userId,const int32_t dlpType,int32_t & appIndex) const1548 ErrCode BundleTestTool::InstallSandboxOperation(
1549     const std::string &bundleName, const int32_t userId, const int32_t dlpType, int32_t &appIndex) const
1550 {
1551     APP_LOGD("InstallSandboxOperation of bundleName %{public}s, dipType is %{public}d", bundleName.c_str(), dlpType);
1552     return bundleInstallerProxy_->InstallSandboxApp(bundleName, dlpType, userId, appIndex);
1553 }
1554 
RunAsInstallSandboxCommand()1555 ErrCode BundleTestTool::RunAsInstallSandboxCommand()
1556 {
1557     int result = OHOS::ERR_OK;
1558     int counter = 0;
1559     std::string commandName = INSTALL_SANDBOX;
1560     std::string bundleName = "";
1561     int32_t userId = 100;
1562     int32_t dlpType = 0;
1563     while (true) {
1564         counter++;
1565         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1566         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1567         if (optind < 0 || optind > argc_) {
1568             return OHOS::ERR_INVALID_VALUE;
1569         }
1570         if (option == -1 || option == '?') {
1571             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1572             break;
1573         } else if (option == 'u') {
1574             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1575                 OHOS::ERR_INVALID_VALUE : result;
1576         } else {
1577             result = !CheckSandboxCorrectOption(option, commandName, dlpType, bundleName) ?
1578                 OHOS::ERR_INVALID_VALUE : result;
1579         }
1580     }
1581 
1582     if (result == OHOS::ERR_OK && bundleName == "") {
1583         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1584         result = OHOS::ERR_INVALID_VALUE;
1585     } else {
1586         APP_LOGD("installSandbox app bundleName is %{public}s", bundleName.c_str());
1587     }
1588 
1589     if (result != OHOS::ERR_OK) {
1590         resultReceiver_.append(HELP_MSG_INSTALL_SANDBOX);
1591         return result;
1592     }
1593 
1594     int32_t appIndex = 0;
1595     auto ret = InstallSandboxOperation(bundleName, userId, dlpType, appIndex);
1596     if (ret == OHOS::ERR_OK) {
1597         resultReceiver_.append(STRING_INSTALL_SANDBOX_SUCCESSFULLY);
1598     } else {
1599         resultReceiver_.append(STRING_INSTALL_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1600     }
1601     return result;
1602 }
1603 
UninstallSandboxOperation(const std::string & bundleName,const int32_t appIndex,const int32_t userId) const1604 ErrCode BundleTestTool::UninstallSandboxOperation(const std::string &bundleName,
1605     const int32_t appIndex, const int32_t userId) const
1606 {
1607     APP_LOGD("UninstallSandboxOperation of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1608     return bundleInstallerProxy_->UninstallSandboxApp(bundleName, appIndex, userId);
1609 }
1610 
RunAsUninstallSandboxCommand()1611 ErrCode BundleTestTool::RunAsUninstallSandboxCommand()
1612 {
1613     int result = OHOS::ERR_OK;
1614     int counter = 0;
1615     std::string bundleName = "";
1616     std::string commandName = UNINSTALL_SANDBOX;
1617     int32_t userId = 100;
1618     int32_t appIndex = -1;
1619     while (true) {
1620         counter++;
1621         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1622         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1623         if (optind < 0 || optind > argc_) {
1624             return OHOS::ERR_INVALID_VALUE;
1625         }
1626 
1627         if (option == -1 || option == '?') {
1628             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1629             break;
1630         } else if (option == 'u') {
1631             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1632                 OHOS::ERR_INVALID_VALUE : result;
1633         } else {
1634             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1635                 OHOS::ERR_INVALID_VALUE : result;
1636         }
1637     }
1638 
1639     if (result == OHOS::ERR_OK && bundleName == "") {
1640         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1641         result = OHOS::ERR_INVALID_VALUE;
1642     } else {
1643         APP_LOGD("uninstallSandbox app bundleName is %{private}s", bundleName.c_str());
1644     }
1645 
1646     if (result != OHOS::ERR_OK) {
1647         resultReceiver_.append(HELP_MSG_UNINSTALL_SANDBOX);
1648         return result;
1649     }
1650 
1651     auto ret = UninstallSandboxOperation(bundleName, appIndex, userId);
1652     if (ret == ERR_OK) {
1653         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_SUCCESSFULLY);
1654     } else {
1655         resultReceiver_.append(STRING_UNINSTALL_SANDBOX_FAILED + "errCode is " + std::to_string(ret) + "\n");
1656     }
1657     return result;
1658 }
1659 
DumpSandboxBundleInfo(const std::string & bundleName,const int32_t appIndex,const int32_t userId,std::string & dumpResults)1660 ErrCode BundleTestTool::DumpSandboxBundleInfo(const std::string &bundleName, const int32_t appIndex,
1661     const int32_t userId, std::string &dumpResults)
1662 {
1663     APP_LOGD("DumpSandboxBundleInfo of bundleName %{public}s_%{public}d", bundleName.c_str(), appIndex);
1664     BundleInfo bundleInfo;
1665     BundleMgrClient client;
1666     auto dumpRet = client.GetSandboxBundleInfo(bundleName, appIndex, userId, bundleInfo);
1667     if (dumpRet == ERR_OK) {
1668         nlohmann::json jsonObject = bundleInfo;
1669         jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
1670         dumpResults= jsonObject.dump(Constants::DUMP_INDENT);
1671     }
1672     return dumpRet;
1673 }
1674 
RunAsDumpSandboxCommand()1675 ErrCode BundleTestTool::RunAsDumpSandboxCommand()
1676 {
1677     int result = OHOS::ERR_OK;
1678     int counter = 0;
1679     std::string bundleName = "";
1680     std::string commandName = DUMP_SANDBOX;
1681     int32_t userId = 100;
1682     int32_t appIndex = -1;
1683     while (true) {
1684         counter++;
1685         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_SANDBOX.c_str(), LONG_OPTIONS_SANDBOX, nullptr);
1686         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1687         if (optind < 0 || optind > argc_) {
1688             return OHOS::ERR_INVALID_VALUE;
1689         }
1690         if (option == -1 || option == '?') {
1691             result = !CheckSandboxErrorOption(option, counter, commandName) ? OHOS::ERR_INVALID_VALUE : result;
1692             break;
1693         } else if (option == 'u') {
1694             result = !CheckSandboxCorrectOption(option, commandName, userId, bundleName) ?
1695                 OHOS::ERR_INVALID_VALUE : result;
1696         } else {
1697             result = !CheckSandboxCorrectOption(option, commandName, appIndex, bundleName) ?
1698                 OHOS::ERR_INVALID_VALUE : result;
1699         }
1700     }
1701 
1702     if (result == OHOS::ERR_OK && bundleName == "") {
1703         resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION);
1704         result = OHOS::ERR_INVALID_VALUE;
1705     } else {
1706         APP_LOGD("dumpSandbox app bundleName is %{public}s", bundleName.c_str());
1707     }
1708 
1709     if (result != OHOS::ERR_OK) {
1710         resultReceiver_.append(HELP_MSG_DUMP_SANDBOX);
1711         return result;
1712     }
1713 
1714     std::string dumpRes = "";
1715     ErrCode ret = DumpSandboxBundleInfo(bundleName, appIndex, userId, dumpRes);
1716     if (ret == ERR_OK) {
1717         resultReceiver_.append(dumpRes + "\n");
1718     } else {
1719         resultReceiver_.append(STRING_DUMP_SANDBOX_FAILED + "errCode is "+ std::to_string(ret) + "\n");
1720     }
1721     return result;
1722 }
1723 
StringToInt(std::string optarg,const std::string & commandName,int & temp,bool & result)1724 ErrCode BundleTestTool::StringToInt(
1725     std::string optarg, const std::string &commandName, int &temp, bool &result)
1726 {
1727     try {
1728         temp = std::stoi(optarg);
1729         if (optind > 0 && optind <= argc_) {
1730             APP_LOGD("bundle_test_tool %{public}s -u user-id:%{public}d, %{public}s",
1731                 commandName.c_str(), temp, argv_[optind - 1]);
1732         }
1733     } catch (const std::exception& e) {
1734         std::cerr << e.what() << std::endl;
1735         result = false;
1736     }
1737     return OHOS::ERR_OK;
1738 }
1739 
StringToUnsignedLongLong(std::string optarg,const std::string & commandName,uint64_t & temp,bool & result)1740 ErrCode BundleTestTool::StringToUnsignedLongLong(
1741     std::string optarg, const std::string &commandName, uint64_t &temp, bool &result)
1742 {
1743     try {
1744         APP_LOGI("StringToUnsignedLongLong start, optarg : %{public}s", optarg.c_str());
1745         if ((optarg == "") || (optarg[0] == '0') || (!isdigit(optarg[0]))) {
1746             resultReceiver_.append("error: parameter error, cache size must be greater than 0\n");
1747             return OHOS::ERR_INVALID_VALUE;
1748         }
1749         temp = std::stoull(optarg);
1750     } catch (const std::exception& e) {
1751         std::cerr << e.what() << std::endl;
1752         result = false;
1753     }
1754     return OHOS::ERR_OK;
1755 }
1756 
HandleUnknownOption(const std::string & commandName,bool & ret)1757 bool BundleTestTool::HandleUnknownOption(const std::string &commandName, bool &ret)
1758 {
1759     std::string unknownOption = "";
1760     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1761     APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1762     resultReceiver_.append(unknownOptionMsg);
1763     return ret = false;
1764 }
1765 
CheckGetStringCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1766 bool BundleTestTool::CheckGetStringCorrectOption(
1767     int option, const std::string &commandName, int &temp, std::string &name)
1768 {
1769     bool ret = true;
1770     switch (option) {
1771         case 'h': {
1772             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1773             ret = false;
1774             break;
1775         }
1776         case 'n': {
1777             name = optarg;
1778             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1779             break;
1780         }
1781         case 'm': {
1782             name = optarg;
1783             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1784                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1785             break;
1786         }
1787         case 'c': {
1788             name = optarg;
1789             APP_LOGD("bundle_test_tool %{public}s -m continue-type:%{public}s, %{public}s",
1790                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
1791             break;
1792         }
1793         case 'u': {
1794             StringToInt(optarg, commandName, temp, ret);
1795             break;
1796         }
1797         case 'a': {
1798             StringToInt(optarg, commandName, temp, ret);
1799             break;
1800         }
1801         case 'p': {
1802             StringToInt(optarg, commandName, temp, ret);
1803             break;
1804         }
1805         case 'i': {
1806             StringToInt(optarg, commandName, temp, ret);
1807             break;
1808         }
1809         default: {
1810             HandleUnknownOption(commandName, ret);
1811             break;
1812         }
1813     }
1814     return ret;
1815 }
1816 
CheckGetProxyDataCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1817 bool BundleTestTool::CheckGetProxyDataCorrectOption(
1818     int option, const std::string &commandName, int &temp, std::string &name)
1819 {
1820     bool ret = true;
1821     switch (option) {
1822         case 'h': {
1823             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1824             ret = false;
1825             break;
1826         }
1827         case 'n': {
1828             name = optarg;
1829             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
1830             break;
1831         }
1832         case 'm': {
1833             name = optarg;
1834             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
1835                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
1836             break;
1837         }
1838         case 'u': {
1839             StringToInt(optarg, commandName, temp, ret);
1840             break;
1841         }
1842         default: {
1843             std::string unknownOption = "";
1844             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1845             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1846             resultReceiver_.append(unknownOptionMsg);
1847             ret = false;
1848             break;
1849         }
1850     }
1851     return ret;
1852 }
1853 
CheckGetAllProxyDataCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)1854 bool BundleTestTool::CheckGetAllProxyDataCorrectOption(
1855     int option, const std::string &commandName, int &temp, std::string &name)
1856 {
1857     bool ret = true;
1858     switch (option) {
1859         case 'h': {
1860             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
1861             ret = false;
1862             break;
1863         }
1864         case 'u': {
1865             StringToInt(optarg, commandName, temp, ret);
1866             break;
1867         }
1868         default: {
1869             std::string unknownOption = "";
1870             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
1871             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
1872             resultReceiver_.append(unknownOptionMsg);
1873             ret = false;
1874             break;
1875         }
1876     }
1877     return ret;
1878 }
1879 
RunAsGetProxyDataCommand()1880 ErrCode BundleTestTool::RunAsGetProxyDataCommand()
1881 {
1882     int result = OHOS::ERR_OK;
1883     int counter = 0;
1884     std::string commandName = "getProxyData";
1885     std::string name = "";
1886     std::string bundleName = "";
1887     std::string moduleName = "";
1888     int userId = Constants::ALL_USERID;
1889     APP_LOGD("RunAsGetProxyDataCommand is start");
1890     while (true) {
1891         counter++;
1892         int32_t option = getopt_long(
1893             argc_, argv_, SHORT_OPTIONS_PROXY_DATA.c_str(), LONG_OPTIONS_PROXY_DATA, nullptr);
1894         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1895         if (optind < 0 || optind > argc_) {
1896             return OHOS::ERR_INVALID_VALUE;
1897         }
1898         if (option == -1) {
1899             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1900                 APP_LOGD("bundle_test_tool getProxyData with no option.");
1901                 resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
1902                 return OHOS::ERR_INVALID_VALUE;
1903             }
1904             break;
1905         }
1906         int temp = 0;
1907         result = !CheckGetProxyDataCorrectOption(option, commandName, temp, name)
1908                  ? OHOS::ERR_INVALID_VALUE : result;
1909         moduleName = option == 'm' ? name : moduleName;
1910         bundleName = option == 'n' ? name : bundleName;
1911         userId = option == 'u' ? temp : userId;
1912     }
1913 
1914     if (result != OHOS::ERR_OK) {
1915         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
1916     } else {
1917         std::vector<ProxyData> proxyDatas;
1918         result = bundleMgrProxy_->GetProxyDataInfos(bundleName, moduleName, proxyDatas, userId);
1919         if (result == ERR_OK) {
1920             nlohmann::json jsonObject = proxyDatas;
1921             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
1922             resultReceiver_.append(results);
1923         } else {
1924             resultReceiver_.append(STRING_GET_PROXY_DATA_NG + " errCode is "+ std::to_string(result) + "\n");
1925         }
1926     }
1927     return result;
1928 }
1929 
RunAsGetAllProxyDataCommand()1930 ErrCode BundleTestTool::RunAsGetAllProxyDataCommand()
1931 {
1932     int result = OHOS::ERR_OK;
1933     int counter = 0;
1934     std::string commandName = "getProxyData";
1935     std::string name = "";
1936     int userId = Constants::ALL_USERID;
1937     APP_LOGD("RunAsGetAllProxyDataCommand is start");
1938     while (true) {
1939         counter++;
1940         int32_t option = getopt_long(
1941             argc_, argv_, SHORT_OPTIONS_ALL_PROXY_DATA.c_str(), LONG_OPTIONS_ALL_PROXY_DATA, nullptr);
1942         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1943         if (optind < 0 || optind > argc_) {
1944             return OHOS::ERR_INVALID_VALUE;
1945         }
1946         if (option == -1) {
1947             break;
1948         }
1949 
1950         int temp = 0;
1951         result = !CheckGetAllProxyDataCorrectOption(option, commandName, temp, name)
1952                  ? OHOS::ERR_INVALID_VALUE : result;
1953         userId = option == 'u' ? temp : userId;
1954     }
1955 
1956     if (result != OHOS::ERR_OK) {
1957         resultReceiver_.append(HELP_MSG_GET_ALL_PROXY_DATA);
1958     } else {
1959         std::vector<ProxyData> proxyDatas;
1960         result = bundleMgrProxy_->GetAllProxyDataInfos(proxyDatas, userId);
1961         if (result == ERR_OK) {
1962             nlohmann::json jsonObject = proxyDatas;
1963             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
1964             resultReceiver_.append(results);
1965         } else {
1966             resultReceiver_.append(STRING_GET_PROXY_DATA_NG + " errCode is "+ std::to_string(result) + "\n");
1967         }
1968     }
1969     return result;
1970 }
1971 
RunAsGetStringCommand()1972 ErrCode BundleTestTool::RunAsGetStringCommand()
1973 {
1974     int result = OHOS::ERR_OK;
1975     int counter = 0;
1976     std::string commandName = "getStr";
1977     std::string name = "";
1978     std::string bundleName = "";
1979     std::string moduleName = "";
1980     int userId = 100;
1981     int labelId = 0;
1982     APP_LOGD("RunAsGetStringCommand is start");
1983     while (true) {
1984         counter++;
1985         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
1986         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
1987         if (optind < 0 || optind > argc_) {
1988             return OHOS::ERR_INVALID_VALUE;
1989         }
1990         if (option == -1) {
1991             // When scanning the first argument
1992             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
1993                 // 'GetStringById' with no option: GetStringById
1994                 // 'GetStringById' with a wrong argument: GetStringById
1995                 APP_LOGD("bundle_test_tool getStr with no option.");
1996                 resultReceiver_.append(HELP_MSG_NO_GETSTRING_OPTION);
1997                 return OHOS::ERR_INVALID_VALUE;
1998             }
1999             break;
2000         }
2001         int temp = 0;
2002         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
2003             ? OHOS::ERR_INVALID_VALUE : result;
2004         moduleName = option == 'm' ? name : moduleName;
2005         bundleName = option == 'n' ? name : bundleName;
2006         userId = option == 'u' ? temp : userId;
2007         labelId = option == 'i' ? temp : labelId;
2008     }
2009 
2010     if (result != OHOS::ERR_OK) {
2011         resultReceiver_.append(HELP_MSG_GET_STRING);
2012     } else {
2013         std::string results = "";
2014         results = bundleMgrProxy_->GetStringById(bundleName, moduleName, labelId, userId);
2015         if (results.empty()) {
2016             resultReceiver_.append(STRING_GET_STRING_NG);
2017             return result;
2018         }
2019         resultReceiver_.append(results);
2020     }
2021     return result;
2022 }
2023 
CheckExtOrMimeCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2024 bool BundleTestTool::CheckExtOrMimeCorrectOption(
2025     int option, const std::string &commandName, int &temp, std::string &name)
2026 {
2027     bool ret = true;
2028     switch (option) {
2029         case 'h': {
2030             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2031             ret = false;
2032             break;
2033         }
2034         case 'n': {
2035             name = optarg;
2036             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
2037             break;
2038         }
2039         case 'm': {
2040             name = optarg;
2041             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
2042                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2043             break;
2044         }
2045         case 'a': {
2046             name = optarg;
2047             APP_LOGD("bundle_test_tool %{public}s -m ability-name:%{public}s, %{public}s",
2048                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2049             break;
2050         }
2051         case 'e': {
2052             name = optarg;
2053             APP_LOGD("bundle_test_tool %{public}s -m ext-name:%{public}s, %{public}s",
2054                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2055             break;
2056         }
2057         case 't': {
2058             name = optarg;
2059             APP_LOGD("bundle_test_tool %{public}s -m mime-type:%{public}s, %{public}s",
2060                      commandName.c_str(), name.c_str(), argv_[optind - 1]);
2061             break;
2062         }
2063         default: {
2064             std::string unknownOption = "";
2065             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2066             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2067             resultReceiver_.append(unknownOptionMsg);
2068             ret = false;
2069             break;
2070         }
2071     }
2072     return ret;
2073 }
2074 
RunAsSetExtNameOrMIMEToAppCommand()2075 ErrCode BundleTestTool::RunAsSetExtNameOrMIMEToAppCommand()
2076 {
2077     int result = OHOS::ERR_OK;
2078     int counter = 0;
2079     std::string commandName = "setExtNameOrMimeToApp";
2080     std::string name = "";
2081     std::string bundleName = "";
2082     std::string moduleName = "";
2083     std::string abilityName = "";
2084     std::string extName = "";
2085     std::string mimeType = "";
2086     APP_LOGD("RunAsSetExtNameOrMIMEToAppCommand is start");
2087     while (true) {
2088         counter++;
2089         int32_t option = getopt_long(
2090             argc_, argv_, SHORT_OPTIONS_MIME.c_str(), LONG_OPTIONS_MIME, nullptr);
2091         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2092         if (optind < 0 || optind > argc_) {
2093             return OHOS::ERR_INVALID_VALUE;
2094         }
2095         if (option == -1) {
2096             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2097                 APP_LOGD("bundle_test_tool RunAsSetExtNameOrMIMEToAppCommand with no option.");
2098                 resultReceiver_.append(HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE);
2099                 return OHOS::ERR_INVALID_VALUE;
2100             }
2101             break;
2102         }
2103         int temp = 0;
2104         result = !CheckExtOrMimeCorrectOption(option, commandName, temp, name)
2105                  ? OHOS::ERR_INVALID_VALUE : result;
2106         moduleName = option == 'm' ? name : moduleName;
2107         bundleName = option == 'n' ? name : bundleName;
2108         abilityName = option == 'a' ? name : abilityName;
2109         extName = option == 'e' ? name : extName;
2110         mimeType = option == 't' ? name : mimeType;
2111     }
2112 
2113     if (result != OHOS::ERR_OK) {
2114         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2115     } else {
2116         result = bundleMgrProxy_->SetExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
2117         if (result == ERR_OK) {
2118             resultReceiver_.append("SetExtNameOrMIMEToApp succeeded,");
2119         } else {
2120             resultReceiver_.append("SetExtNameOrMIMEToApp failed, errCode is "+ std::to_string(result) + "\n");
2121         }
2122     }
2123     return result;
2124 }
2125 
RunAsDelExtNameOrMIMEToAppCommand()2126 ErrCode BundleTestTool::RunAsDelExtNameOrMIMEToAppCommand()
2127 {
2128     int result = OHOS::ERR_OK;
2129     int counter = 0;
2130     std::string commandName = "delExtNameOrMimeToApp";
2131     std::string name = "";
2132     std::string bundleName = "";
2133     std::string moduleName = "";
2134     std::string abilityName = "";
2135     std::string extName = "";
2136     std::string mimeType = "";
2137     APP_LOGD("RunAsDelExtNameOrMIMEToAppCommand is start");
2138     while (true) {
2139         counter++;
2140         int32_t option = getopt_long(
2141             argc_, argv_, SHORT_OPTIONS_MIME.c_str(), LONG_OPTIONS_MIME, nullptr);
2142         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2143         if (optind < 0 || optind > argc_) {
2144             return OHOS::ERR_INVALID_VALUE;
2145         }
2146         if (option == -1) {
2147             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2148                 APP_LOGD("bundle_test_tool RunAsDelExtNameOrMIMEToAppCommand with no option.");
2149                 resultReceiver_.append(HELP_MSG_SET_EXT_NAME_OR_MIME_TYPE);
2150                 return OHOS::ERR_INVALID_VALUE;
2151             }
2152             break;
2153         }
2154         int temp = 0;
2155         result = !CheckExtOrMimeCorrectOption(option, commandName, temp, name)
2156                  ? OHOS::ERR_INVALID_VALUE : result;
2157         moduleName = option == 'm' ? name : moduleName;
2158         bundleName = option == 'n' ? name : bundleName;
2159         abilityName = option == 'a' ? name : abilityName;
2160         extName = option == 'e' ? name : extName;
2161         mimeType = option == 't' ? name : mimeType;
2162     }
2163 
2164     if (result != OHOS::ERR_OK) {
2165         resultReceiver_.append(HELP_MSG_GET_PROXY_DATA);
2166     } else {
2167         result = bundleMgrProxy_->DelExtNameOrMIMEToApp(bundleName, moduleName, abilityName, extName, mimeType);
2168         if (result == ERR_OK) {
2169             resultReceiver_.append("DelExtNameOrMIMEToApp succeeded");
2170         } else {
2171             resultReceiver_.append("DelExtNameOrMIMEToApp failed, errCode is "+ std::to_string(result) + "\n");
2172         }
2173     }
2174     return result;
2175 }
2176 
CheckGetIconCorrectOption(int option,const std::string & commandName,int & temp,std::string & name)2177 bool BundleTestTool::CheckGetIconCorrectOption(
2178     int option, const std::string &commandName, int &temp, std::string &name)
2179 {
2180     bool ret = true;
2181     switch (option) {
2182         case 'h': {
2183             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2184             ret = false;
2185             break;
2186         }
2187         case 'n': {
2188             name = optarg;
2189             APP_LOGD("bundle_test_tool %{public}s -n %{public}s", commandName.c_str(), argv_[optind - 1]);
2190             break;
2191         }
2192         case 'm': {
2193             name = optarg;
2194             APP_LOGD("bundle_test_tool %{public}s -m module-name:%{public}s, %{public}s",
2195                 commandName.c_str(), name.c_str(), argv_[optind - 1]);
2196             break;
2197         }
2198         case 'u': {
2199             StringToInt(optarg, commandName, temp, ret);
2200             break;
2201         }
2202         case 'i': {
2203             StringToInt(optarg, commandName, temp, ret);
2204             break;
2205         }
2206         case 'd': {
2207             StringToInt(optarg, commandName, temp, ret);
2208             break;
2209         }
2210         default: {
2211             std::string unknownOption = "";
2212             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2213             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2214             resultReceiver_.append(unknownOptionMsg);
2215             ret = false;
2216             break;
2217         }
2218     }
2219     return ret;
2220 }
2221 
RunAsGetIconCommand()2222 ErrCode BundleTestTool::RunAsGetIconCommand()
2223 {
2224     int result = OHOS::ERR_OK;
2225     int counter = 0;
2226     std::string commandName = "getIcon";
2227     std::string name = "";
2228     std::string bundleName = "";
2229     std::string moduleName = "";
2230     int userId = 100;
2231     int iconId = 0;
2232     int density = 0;
2233     APP_LOGD("RunAsGetIconCommand is start");
2234     while (true) {
2235         counter++;
2236         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET.c_str(), LONG_OPTIONS_GET, nullptr);
2237         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2238         if (optind < 0 || optind > argc_) {
2239             return OHOS::ERR_INVALID_VALUE;
2240         }
2241         if (option == -1) {
2242             // When scanning the first argument
2243             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2244                 // 'GetIconById' with no option: GetStringById
2245                 // 'GetIconById' with a wrong argument: GetStringById
2246                 APP_LOGD("bundle_test_tool getIcon with no option.");
2247                 resultReceiver_.append(HELP_MSG_NO_GETICON_OPTION);
2248                 return OHOS::ERR_INVALID_VALUE;
2249             }
2250             break;
2251         }
2252         int temp = 0;
2253         result = !CheckGetIconCorrectOption(option, commandName, temp, name)
2254             ? OHOS::ERR_INVALID_VALUE : result;
2255         moduleName = option == 'm' ? name : moduleName;
2256         bundleName = option == 'n' ? name : bundleName;
2257         userId = option == 'u' ? temp : userId;
2258         iconId = option == 'i' ? temp : iconId;
2259         density = option == 'd' ? temp : density;
2260     }
2261 
2262     if (result != OHOS::ERR_OK) {
2263         resultReceiver_.append(HELP_MSG_GET_ICON);
2264     } else {
2265         std::string results = "";
2266         results = bundleMgrProxy_->GetIconById(bundleName, moduleName, iconId, density, userId);
2267         if (results.empty()) {
2268             resultReceiver_.append(STRING_GET_ICON_NG);
2269             return result;
2270         }
2271         resultReceiver_.append(results);
2272     }
2273     return result;
2274 }
2275 
CheckAddInstallRuleCorrectOption(int option,const std::string & commandName,std::vector<std::string> & appIds,int & controlRuleType,int & userId,int & euid)2276 ErrCode BundleTestTool::CheckAddInstallRuleCorrectOption(int option, const std::string &commandName,
2277     std::vector<std::string> &appIds, int &controlRuleType, int &userId, int &euid)
2278 {
2279     bool ret = true;
2280     switch (option) {
2281         case 'h': {
2282             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2283             return OHOS::ERR_INVALID_VALUE;
2284         }
2285         case 'a': {
2286             std::string arrayAppId = optarg;
2287             std::stringstream array(arrayAppId);
2288             std::string object;
2289             while (getline(array, object, ',')) {
2290                 appIds.emplace_back(object);
2291             }
2292             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
2293             break;
2294         }
2295         case 'e': {
2296             StringToInt(optarg, commandName, euid, ret);
2297             break;
2298         }
2299         case 't': {
2300             StringToInt(optarg, commandName, controlRuleType, ret);
2301             break;
2302         }
2303         case 'u': {
2304             StringToInt(optarg, commandName, userId, ret);
2305             break;
2306         }
2307         default: {
2308             std::string unknownOption = "";
2309             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2310             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2311             resultReceiver_.append(unknownOptionMsg);
2312             return OHOS::ERR_INVALID_VALUE;
2313         }
2314     }
2315     return OHOS::ERR_OK;
2316 }
2317 
2318 // bundle_test_tool addAppInstallRule -a test1,test2 -t 1 -u 101 -e 3057
RunAsAddInstallRuleCommand()2319 ErrCode BundleTestTool::RunAsAddInstallRuleCommand()
2320 {
2321     ErrCode result = OHOS::ERR_OK;
2322     int counter = 0;
2323     std::string commandName = "addAppInstallRule";
2324     std::vector<std::string> appIds;
2325     int euid = 3057;
2326     int userId = 100;
2327     int ruleType = 0;
2328     APP_LOGD("RunAsAddInstallRuleCommand is start");
2329     while (true) {
2330         counter++;
2331         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2332         if (optind < 0 || optind > argc_) {
2333             return OHOS::ERR_INVALID_VALUE;
2334         }
2335         if (option == -1) {
2336             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2337                 resultReceiver_.append(HELP_MSG_NO_ADD_INSTALL_RULE_OPTION);
2338                 return OHOS::ERR_INVALID_VALUE;
2339             }
2340             break;
2341         }
2342         result = CheckAddInstallRuleCorrectOption(option, commandName, appIds, ruleType, userId, euid);
2343         if (result != OHOS::ERR_OK) {
2344             resultReceiver_.append(HELP_MSG_ADD_INSTALL_RULE);
2345             return OHOS::ERR_INVALID_VALUE;
2346         }
2347     }
2348     seteuid(euid);
2349     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2350     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2351     if (!appControlProxy) {
2352         APP_LOGE("fail to get app control proxy.");
2353         return OHOS::ERR_INVALID_VALUE;
2354     }
2355     std::string appIdParam = "";
2356     for (auto param : appIds) {
2357         appIdParam = appIdParam.append(param) + ";";
2358     }
2359     APP_LOGI("appIds: %{public}s, controlRuleType: %{public}d, userId: %{public}d",
2360         appIdParam.c_str(), ruleType, userId);
2361     int32_t res = appControlProxy->AddAppInstallControlRule(appIds, rule, userId);
2362     APP_LOGI("AddAppInstallControlRule return code: %{public}d", res);
2363     if (res != OHOS::ERR_OK) {
2364         resultReceiver_.append(STRING_ADD_RULE_NG);
2365         return res;
2366     }
2367     resultReceiver_.append(std::to_string(res) + "\n");
2368     return result;
2369 }
2370 
CheckGetInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)2371 ErrCode BundleTestTool::CheckGetInstallRuleCorrectOption(int option, const std::string &commandName,
2372     int &controlRuleType, int &userId, int &euid)
2373 {
2374     bool ret = true;
2375     switch (option) {
2376         case 'h': {
2377             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2378             return OHOS::ERR_INVALID_VALUE;
2379         }
2380         case 'e': {
2381             StringToInt(optarg, commandName, euid, ret);
2382             break;
2383         }
2384         case 't': {
2385             StringToInt(optarg, commandName, controlRuleType, ret);
2386             break;
2387         }
2388         case 'u': {
2389             StringToInt(optarg, commandName, userId, ret);
2390             break;
2391         }
2392         default: {
2393             std::string unknownOption = "";
2394             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2395             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2396             resultReceiver_.append(unknownOptionMsg);
2397             return OHOS::ERR_INVALID_VALUE;
2398         }
2399     }
2400     return OHOS::ERR_OK;
2401 }
2402 
2403 // bundle_test_tool getAppInstallRule -t 1 -u 101 -e 3057
RunAsGetInstallRuleCommand()2404 ErrCode BundleTestTool::RunAsGetInstallRuleCommand()
2405 {
2406     ErrCode result = OHOS::ERR_OK;
2407     int counter = 0;
2408     std::string commandName = "getAppInstallRule";
2409     int euid = 3057;
2410     int userId = 100;
2411     int ruleType = 0;
2412     APP_LOGD("RunAsGetInstallRuleCommand is start");
2413     while (true) {
2414         counter++;
2415         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2416         if (optind < 0 || optind > argc_) {
2417             return OHOS::ERR_INVALID_VALUE;
2418         }
2419         if (option == -1) {
2420             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2421                 resultReceiver_.append(HELP_MSG_NO_GET_INSTALL_RULE_OPTION);
2422                 return OHOS::ERR_INVALID_VALUE;
2423             }
2424             break;
2425         }
2426         result = CheckGetInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
2427         if (result != OHOS::ERR_OK) {
2428             resultReceiver_.append(HELP_MSG_GET_INSTALL_RULE);
2429             return OHOS::ERR_INVALID_VALUE;
2430         }
2431     }
2432     seteuid(euid);
2433     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2434     if (!appControlProxy) {
2435         APP_LOGE("fail to get app control proxy.");
2436         return OHOS::ERR_INVALID_VALUE;
2437     }
2438     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
2439     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2440     std::vector<std::string> appIds;
2441     int32_t res = appControlProxy->GetAppInstallControlRule(rule, userId, appIds);
2442     APP_LOGI("GetAppInstallControlRule return code: %{public}d", res);
2443     if (res != OHOS::ERR_OK) {
2444         resultReceiver_.append(STRING_GET_RULE_NG);
2445         return res;
2446     }
2447     std::string appIdParam = "";
2448     for (auto param : appIds) {
2449         appIdParam = appIdParam.append(param) + "; ";
2450     }
2451     resultReceiver_.append("appId : " + appIdParam + "\n");
2452     return result;
2453 }
2454 
CheckDeleteInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,std::vector<std::string> & appIds,int & userId,int & euid)2455 ErrCode BundleTestTool::CheckDeleteInstallRuleCorrectOption(int option, const std::string &commandName,
2456     int &controlRuleType, std::vector<std::string> &appIds, int &userId, int &euid)
2457 {
2458     bool ret = true;
2459     switch (option) {
2460         case 'h': {
2461             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2462             return OHOS::ERR_INVALID_VALUE;
2463         }
2464         case 'a': {
2465             std::string arrayAppId = optarg;
2466             std::stringstream array(arrayAppId);
2467             std::string object;
2468             while (getline(array, object, ',')) {
2469                 appIds.emplace_back(object);
2470             }
2471             APP_LOGD("bundle_test_tool %{public}s -a %{public}s", commandName.c_str(), argv_[optind - 1]);
2472             break;
2473         }
2474         case 'e': {
2475             StringToInt(optarg, commandName, euid, ret);
2476             break;
2477         }
2478         case 't': {
2479             StringToInt(optarg, commandName, controlRuleType, ret);
2480             break;
2481         }
2482         case 'u': {
2483             StringToInt(optarg, commandName, userId, ret);
2484             break;
2485         }
2486         default: {
2487             std::string unknownOption = "";
2488             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2489             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2490             resultReceiver_.append(unknownOptionMsg);
2491             return OHOS::ERR_INVALID_VALUE;
2492         }
2493     }
2494     return OHOS::ERR_OK;
2495 }
2496 
2497 // bundle_test_tool deleteAppInstallRule -a test1 -t 1 -u 101 -e 3057
RunAsDeleteInstallRuleCommand()2498 ErrCode BundleTestTool::RunAsDeleteInstallRuleCommand()
2499 {
2500     ErrCode result = OHOS::ERR_OK;
2501     int counter = 0;
2502     int euid = 3057;
2503     std::string commandName = "deleteAppInstallRule";
2504     std::vector<std::string> appIds;
2505     int ruleType = 0;
2506     int userId = 100;
2507     APP_LOGD("RunAsDeleteInstallRuleCommand is start");
2508     while (true) {
2509         counter++;
2510         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2511         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2512         if (optind < 0 || optind > argc_) {
2513             return OHOS::ERR_INVALID_VALUE;
2514         }
2515         if (option == -1) {
2516             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2517                 resultReceiver_.append(HELP_MSG_NO_DELETE_INSTALL_RULE_OPTION);
2518                 return OHOS::ERR_INVALID_VALUE;
2519             }
2520             break;
2521         }
2522         result = CheckDeleteInstallRuleCorrectOption(option, commandName, ruleType, appIds, userId, euid);
2523         if (result != OHOS::ERR_OK) {
2524             resultReceiver_.append(HELP_MSG_DELETE_INSTALL_RULE);
2525             return OHOS::ERR_INVALID_VALUE;
2526         }
2527     }
2528     seteuid(euid);
2529     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2530     if (!appControlProxy) {
2531         APP_LOGE("fail to get app control proxy.");
2532         return OHOS::ERR_INVALID_VALUE;
2533     }
2534     std::string appIdParam = "";
2535     for (auto param : appIds) {
2536         appIdParam = appIdParam.append(param) + ";";
2537     }
2538     APP_LOGI("appIds: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2539     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2540     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, appIds, userId);
2541     APP_LOGI("DeleteAppInstallControlRule return code: %{public}d", res);
2542     if (res != OHOS::ERR_OK) {
2543         resultReceiver_.append(STRING_DELETE_RULE_NG);
2544         return res;
2545     }
2546     resultReceiver_.append(std::to_string(res) + "\n");
2547     return result;
2548 }
2549 
CheckCleanInstallRuleCorrectOption(int option,const std::string & commandName,int & controlRuleType,int & userId,int & euid)2550 ErrCode BundleTestTool::CheckCleanInstallRuleCorrectOption(
2551     int option, const std::string &commandName, int &controlRuleType, int &userId, int &euid)
2552 {
2553     bool ret = true;
2554     switch (option) {
2555         case 'h': {
2556             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2557             return OHOS::ERR_INVALID_VALUE;
2558         }
2559         case 'e': {
2560             StringToInt(optarg, commandName, euid, ret);
2561             break;
2562         }
2563         case 't': {
2564             StringToInt(optarg, commandName, controlRuleType, ret);
2565             break;
2566         }
2567         case 'u': {
2568             StringToInt(optarg, commandName, userId, ret);
2569             break;
2570         }
2571         default: {
2572             std::string unknownOption = "";
2573             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2574             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2575             resultReceiver_.append(unknownOptionMsg);
2576             return OHOS::ERR_INVALID_VALUE;
2577         }
2578     }
2579     return OHOS::ERR_OK;
2580 }
2581 
2582 // bundle_test_tool cleanAppInstallRule -t 1 -u 101 -e 3057
RunAsCleanInstallRuleCommand()2583 ErrCode BundleTestTool::RunAsCleanInstallRuleCommand()
2584 {
2585     ErrCode result = OHOS::ERR_OK;
2586     int counter = 0;
2587     int euid = 3057;
2588     std::string commandName = "cleanAppInstallRule";
2589     int userId = 100;
2590     int ruleType = 0;
2591     APP_LOGD("RunAsCleanInstallRuleCommand is start");
2592     while (true) {
2593         counter++;
2594         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2595         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2596         if (optind < 0 || optind > argc_) {
2597             return OHOS::ERR_INVALID_VALUE;
2598         }
2599         if (option == -1) {
2600             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2601                 APP_LOGD("bundle_test_tool getRule with no option.");
2602                 resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
2603                 return OHOS::ERR_INVALID_VALUE;
2604             }
2605             break;
2606         }
2607         result = CheckCleanInstallRuleCorrectOption(option, commandName, ruleType, userId, euid);
2608         if (result != OHOS::ERR_OK) {
2609             resultReceiver_.append(HELP_MSG_NO_CLEAN_INSTALL_RULE_OPTION);
2610             return OHOS::ERR_INVALID_VALUE;
2611         }
2612     }
2613     seteuid(euid);
2614     auto rule = static_cast<AppInstallControlRuleType>(ruleType);
2615     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2616     if (!appControlProxy) {
2617         APP_LOGE("fail to get app control proxy.");
2618         return OHOS::ERR_INVALID_VALUE;
2619     }
2620     APP_LOGI("controlRuleType: %{public}d, userId: %{public}d", ruleType, userId);
2621     int32_t res = appControlProxy->DeleteAppInstallControlRule(rule, userId);
2622     APP_LOGI("DeleteAppInstallControlRule clean return code: %{public}d", res);
2623     if (res != OHOS::ERR_OK) {
2624         resultReceiver_.append(STRING_DELETE_RULE_NG);
2625         return res;
2626     }
2627     resultReceiver_.append(std::to_string(res) + "\n");
2628     return result;
2629 }
2630 
CheckAppRunningRuleCorrectOption(int option,const std::string & commandName,std::vector<AppRunningControlRule> & controlRule,int & userId,int & euid)2631 ErrCode BundleTestTool::CheckAppRunningRuleCorrectOption(int option, const std::string &commandName,
2632     std::vector<AppRunningControlRule> &controlRule, int &userId, int &euid)
2633 {
2634     bool ret = true;
2635     switch (option) {
2636         case 'h': {
2637             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2638             return OHOS::ERR_INVALID_VALUE;
2639         }
2640         case 'c': {
2641             std::string arrayJsonRule = optarg;
2642             std::stringstream array(arrayJsonRule);
2643             std::string object;
2644             while (getline(array, object, ';')) {
2645                 size_t pos1 = object.find("appId");
2646                 size_t pos2 = object.find("controlMessage");
2647                 size_t pos3 = object.find(":", pos2);
2648                 if ((pos1 == std::string::npos) || (pos2 == std::string::npos)) {
2649                     return OHOS::ERR_INVALID_VALUE;
2650                 }
2651                 std::string appId = object.substr(pos1+6, pos2-pos1-7);
2652                 std::string controlMessage = object.substr(pos3+1);
2653                 AppRunningControlRule rule;
2654                 rule.appId = appId;
2655                 rule.controlMessage = controlMessage;
2656                 controlRule.emplace_back(rule);
2657             }
2658             break;
2659         }
2660         case 'e': {
2661             StringToInt(optarg, commandName, euid, ret);
2662             break;
2663         }
2664         case 'u': {
2665             StringToInt(optarg, commandName, userId, ret);
2666             break;
2667         }
2668         default: {
2669             std::string unknownOption = "";
2670             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2671             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2672             resultReceiver_.append(unknownOptionMsg);
2673             return OHOS::ERR_INVALID_VALUE;
2674         }
2675     }
2676     return OHOS::ERR_OK;
2677 }
2678 
2679 // bundle_test_tool addAppRunningRule -c appId:id1,controlMessage:msg1;appId:id2,controlMessage:msg2
2680 // -u 101 -e 3057
RunAsAddAppRunningRuleCommand()2681 ErrCode BundleTestTool::RunAsAddAppRunningRuleCommand()
2682 {
2683     ErrCode result = OHOS::ERR_OK;
2684     int counter = 0;
2685     int euid = 3057;
2686     std::string commandName = "addAppRunningRule";
2687     int userId = 100;
2688     std::vector<AppRunningControlRule> controlRule;
2689     APP_LOGD("RunAsAddAppRunningRuleCommand is start");
2690     while (true) {
2691         counter++;
2692         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2693         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2694         if (optind < 0 || optind > argc_) {
2695             return OHOS::ERR_INVALID_VALUE;
2696         }
2697         if (option == -1) {
2698             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2699                 APP_LOGD("bundle_test_tool getRule with no option.");
2700                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
2701                 return OHOS::ERR_INVALID_VALUE;
2702             }
2703             break;
2704         }
2705         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
2706         if (result != OHOS::ERR_OK) {
2707             resultReceiver_.append(HELP_MSG_ADD_APP_RUNNING_RULE);
2708             return OHOS::ERR_INVALID_VALUE;
2709         }
2710     }
2711     seteuid(euid);
2712     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2713     if (!appControlProxy) {
2714         APP_LOGE("fail to get app control proxy.");
2715         return OHOS::ERR_INVALID_VALUE;
2716     }
2717     std::string appIdParam = "";
2718     for (auto param : controlRule) {
2719         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
2720     }
2721     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2722     int32_t res = appControlProxy->AddAppRunningControlRule(controlRule, userId);
2723     if (res != OHOS::ERR_OK) {
2724         resultReceiver_.append(STRING_ADD_RULE_NG);
2725         return res;
2726     }
2727     resultReceiver_.append(std::to_string(res) + "\n");
2728     return result;
2729 }
2730 
2731 // bundle_test_tool deleteAppRunningRule -c appId:101,controlMessage:msg1 -u 101 -e 3057
RunAsDeleteAppRunningRuleCommand()2732 ErrCode BundleTestTool::RunAsDeleteAppRunningRuleCommand()
2733 {
2734     ErrCode result = OHOS::ERR_OK;
2735     int counter = 0;
2736     int euid = 3057;
2737     std::string commandName = "addAppRunningRule";
2738     int userId = 100;
2739     std::vector<AppRunningControlRule> controlRule;
2740     APP_LOGD("RunAsDeleteAppRunningRuleCommand is start");
2741     while (true) {
2742         counter++;
2743         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2744         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2745         if (optind < 0 || optind > argc_) {
2746             return OHOS::ERR_INVALID_VALUE;
2747         }
2748         if (option == -1) {
2749             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2750                 APP_LOGD("bundle_test_tool getRule with no option.");
2751                 resultReceiver_.append(HELP_MSG_NO_APP_RUNNING_RULE_OPTION);
2752                 return OHOS::ERR_INVALID_VALUE;
2753             }
2754             break;
2755         }
2756         result = CheckAppRunningRuleCorrectOption(option, commandName, controlRule, userId, euid);
2757         if (result != OHOS::ERR_OK) {
2758             resultReceiver_.append(HELP_MSG_DELETE_APP_RUNNING_RULE);
2759             return OHOS::ERR_INVALID_VALUE;
2760         }
2761     }
2762     seteuid(euid);
2763     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2764     if (!appControlProxy) {
2765         APP_LOGE("fail to get app control proxy.");
2766         return OHOS::ERR_INVALID_VALUE;
2767     }
2768     std::string appIdParam = "";
2769     for (auto param : controlRule) {
2770         appIdParam = appIdParam.append("appId:"+ param.appId + ":" + "message" + param.controlMessage);
2771     }
2772     APP_LOGI("appRunningControlRule: %{public}s, userId: %{public}d", appIdParam.c_str(), userId);
2773     int32_t res = appControlProxy->DeleteAppRunningControlRule(controlRule, userId);
2774     if (res != OHOS::ERR_OK) {
2775         resultReceiver_.append(STRING_DELETE_RULE_NG);
2776         return res;
2777     }
2778     resultReceiver_.append(std::to_string(res) + "\n");
2779     return result;
2780 }
2781 
CheckCleanAppRunningRuleCorrectOption(int option,const std::string & commandName,int & userId,int & euid)2782 ErrCode BundleTestTool::CheckCleanAppRunningRuleCorrectOption(
2783     int option, const std::string &commandName, int &userId, int &euid)
2784 {
2785     bool ret = true;
2786     switch (option) {
2787         case 'h': {
2788             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2789             return OHOS::ERR_INVALID_VALUE;
2790         }
2791         case 'e': {
2792             StringToInt(optarg, commandName, euid, ret);
2793             break;
2794         }
2795         case 'u': {
2796             StringToInt(optarg, commandName, userId, ret);
2797             break;
2798         }
2799         default: {
2800             std::string unknownOption = "";
2801             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2802             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2803             resultReceiver_.append(unknownOptionMsg);
2804             return OHOS::ERR_INVALID_VALUE;
2805         }
2806     }
2807     return OHOS::ERR_OK;
2808 }
2809 
2810 // bundle_test_tool cleanAppRunningRule -u 101 -e 3057
RunAsCleanAppRunningRuleCommand()2811 ErrCode BundleTestTool::RunAsCleanAppRunningRuleCommand()
2812 {
2813     ErrCode result = OHOS::ERR_OK;
2814     int counter = 0;
2815     int euid = 3057;
2816     std::string commandName = "addAppRunningRule";
2817     int userId = 100;
2818     APP_LOGD("RunAsCleanAppRunningRuleCommand is start");
2819     while (true) {
2820         counter++;
2821         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2822         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2823         if (optind < 0 || optind > argc_) {
2824             return OHOS::ERR_INVALID_VALUE;
2825         }
2826         if (option == -1) {
2827             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2828                 APP_LOGD("bundle_test_tool getRule with no option.");
2829                 resultReceiver_.append(HELP_MSG_NO_CLEAN_APP_RUNNING_RULE_OPTION);
2830                 return OHOS::ERR_INVALID_VALUE;
2831             }
2832             break;
2833         }
2834         result = CheckCleanAppRunningRuleCorrectOption(option, commandName, userId, euid);
2835         if (result != OHOS::ERR_OK) {
2836             resultReceiver_.append(HELP_MSG_CLEAN_APP_RUNNING_RULE);
2837             return OHOS::ERR_INVALID_VALUE;
2838         }
2839     }
2840     seteuid(euid);
2841     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2842     if (!appControlProxy) {
2843         APP_LOGE("fail to get app control proxy.");
2844         return OHOS::ERR_INVALID_VALUE;
2845     }
2846     APP_LOGI("userId: %{public}d", userId);
2847     int32_t res = appControlProxy->DeleteAppRunningControlRule(userId);
2848     if (res != OHOS::ERR_OK) {
2849         resultReceiver_.append(STRING_DELETE_RULE_NG);
2850         return res;
2851     }
2852     resultReceiver_.append(std::to_string(res) + "\n");
2853     return result;
2854 }
2855 
CheckGetAppRunningRuleCorrectOption(int option,const std::string & commandName,int32_t & userId,int & euid)2856 ErrCode BundleTestTool::CheckGetAppRunningRuleCorrectOption(int option, const std::string &commandName,
2857     int32_t &userId, int &euid)
2858 {
2859     bool ret = true;
2860     switch (option) {
2861         case 'h': {
2862             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2863             return OHOS::ERR_INVALID_VALUE;
2864         }
2865         case 'e': {
2866             StringToInt(optarg, commandName, euid, ret);
2867             break;
2868         }
2869         case 'u': {
2870             StringToInt(optarg, commandName, userId, ret);
2871             break;
2872         }
2873         default: {
2874             std::string unknownOption = "";
2875             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2876             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2877             resultReceiver_.append(unknownOptionMsg);
2878             return OHOS::ERR_INVALID_VALUE;
2879         }
2880     }
2881     return OHOS::ERR_OK ;
2882 }
2883 
2884 // bundle_test_tool getAppRunningControlRule -u 101 -e 3057
RunAsGetAppRunningControlRuleCommand()2885 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleCommand()
2886 {
2887     ErrCode result = OHOS::ERR_OK;
2888     int counter = 0;
2889     int euid = 3057;
2890     std::string commandName = "addAppRunningRule";
2891     int userId = 100;
2892     APP_LOGD("RunAsGetAppRunningControlRuleCommand is start");
2893     while (true) {
2894         counter++;
2895         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2896         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2897         if (optind < 0 || optind > argc_) {
2898             return OHOS::ERR_INVALID_VALUE;
2899         }
2900         if (option == -1) {
2901             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2902                 APP_LOGD("bundle_test_tool getRule with no option.");
2903                 resultReceiver_.append(HELP_MSG_NO_GET_ALL_APP_RUNNING_RULE_OPTION);
2904                 return OHOS::ERR_INVALID_VALUE;
2905             }
2906             break;
2907         }
2908         result = CheckGetAppRunningRuleCorrectOption(option, commandName, userId, euid);
2909         if (result != OHOS::ERR_OK) {
2910             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RULE);
2911             return OHOS::ERR_INVALID_VALUE;
2912         }
2913     }
2914     seteuid(euid);
2915     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
2916     if (!appControlProxy) {
2917         APP_LOGE("fail to get app control proxy.");
2918         return OHOS::ERR_INVALID_VALUE;
2919     }
2920     APP_LOGI("userId: %{public}d", userId);
2921     std::vector<std::string> appIds;
2922     int32_t res = appControlProxy->GetAppRunningControlRule(userId, appIds);
2923     if (res != OHOS::ERR_OK) {
2924         resultReceiver_.append(STRING_GET_RULE_NG);
2925         return res;
2926     }
2927     std::string appIdParam = "";
2928     for (auto param : appIds) {
2929         appIdParam = appIdParam.append(param) + "; ";
2930     }
2931     resultReceiver_.append("appId : " + appIdParam + "\n");
2932     return result;
2933 }
2934 
CheckGetAppRunningRuleResultCorrectOption(int option,const std::string & commandName,std::string & bundleName,int32_t & userId,int & euid)2935 ErrCode BundleTestTool::CheckGetAppRunningRuleResultCorrectOption(int option, const std::string &commandName,
2936     std::string &bundleName, int32_t &userId, int &euid)
2937 {
2938     bool ret = true;
2939     switch (option) {
2940         case 'h': {
2941             APP_LOGD("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
2942             return OHOS::ERR_INVALID_VALUE;
2943         }
2944         case 'e': {
2945             StringToInt(optarg, commandName, euid, ret);
2946             break;
2947         }
2948         case 'n': {
2949             APP_LOGD("'bundle_test_tool %{public}s %{public}s'", commandName.c_str(), argv_[optind - 1]);
2950             bundleName = optarg;
2951             break;
2952         }
2953         case 'u': {
2954             StringToInt(optarg, commandName, userId, ret);
2955             break;
2956         }
2957         default: {
2958             std::string unknownOption = "";
2959             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
2960             APP_LOGD("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
2961             resultReceiver_.append(unknownOptionMsg);
2962             return OHOS::ERR_INVALID_VALUE;
2963         }
2964     }
2965     return OHOS::ERR_OK;
2966 }
2967 
2968 // bundle_test_tool getAppRunningControlRuleResult -n com.ohos.example -e 3057
RunAsGetAppRunningControlRuleResultCommand()2969 ErrCode BundleTestTool::RunAsGetAppRunningControlRuleResultCommand()
2970 {
2971     ErrCode result = OHOS::ERR_OK;
2972     int counter = 0;
2973     int euid = 3057;
2974     std::string commandName = "addAppRunningRule";
2975     int userId = 100;
2976     std::string bundleName;
2977     APP_LOGD("RunAsGetAppRunningControlRuleResultCommand is start");
2978     while (true) {
2979         counter++;
2980         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_RULE.c_str(), LONG_OPTIONS_RULE, nullptr);
2981         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
2982         if (optind < 0 || optind > argc_) {
2983             return OHOS::ERR_INVALID_VALUE;
2984         }
2985         if (option == -1) {
2986             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
2987                 APP_LOGD("bundle_test_tool getRule with no option.");
2988                 resultReceiver_.append(HELP_MSG_NO_GET_APP_RUNNING_RULE_OPTION);
2989                 return OHOS::ERR_INVALID_VALUE;
2990             }
2991             break;
2992         }
2993         result = CheckGetAppRunningRuleResultCorrectOption(option, commandName, bundleName, userId, euid);
2994         if (result != OHOS::ERR_OK) {
2995             resultReceiver_.append(HELP_MSG_GET_APP_RUNNING_RESULT_RULE);
2996             return OHOS::ERR_INVALID_VALUE;
2997         }
2998     }
2999     seteuid(euid);
3000     auto appControlProxy = bundleMgrProxy_->GetAppControlProxy();
3001     if (!appControlProxy) {
3002         APP_LOGE("fail to get app control proxy.");
3003         return OHOS::ERR_INVALID_VALUE;
3004     }
3005     AppRunningControlRuleResult ruleResult;
3006     APP_LOGI("bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
3007     int32_t res = appControlProxy->GetAppRunningControlRule(bundleName, userId, ruleResult);
3008     if (res != OHOS::ERR_OK) {
3009         APP_LOGI("GetAppRunningControlRule result: %{public}d", res);
3010         resultReceiver_.append("message:" + ruleResult.controlMessage + " bundle:notFind" + "\n");
3011         return res;
3012     }
3013     resultReceiver_.append("message:" + ruleResult.controlMessage + "\n");
3014     if (ruleResult.controlWant != nullptr) {
3015         resultReceiver_.append("controlWant:" + ruleResult.controlWant->ToString() + "\n");
3016     } else {
3017         resultReceiver_.append("controlWant: nullptr \n");
3018     }
3019     return result;
3020 }
3021 
CheckCleanBundleCacheFilesAutomaticOption(int option,const std::string & commandName,uint64_t & cacheSize)3022 ErrCode BundleTestTool::CheckCleanBundleCacheFilesAutomaticOption(
3023     int option, const std::string &commandName, uint64_t &cacheSize)
3024 {
3025     bool ret = true;
3026     switch (option) {
3027         case 'h': {
3028             APP_LOGI("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
3029             return OHOS::ERR_INVALID_VALUE;
3030         }
3031         case 's': {
3032             APP_LOGI("bundle_test_tool %{public}s %{public}s", commandName.c_str(), argv_[optind - 1]);
3033             StringToUnsignedLongLong(optarg, commandName, cacheSize, ret);
3034             break;
3035         }
3036         default: {
3037             std::string unknownOption = "";
3038             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3039             APP_LOGE("bundle_test_tool %{public}s with an unknown option.", commandName.c_str());
3040             resultReceiver_.append(unknownOptionMsg);
3041             return OHOS::ERR_INVALID_VALUE;
3042         }
3043     }
3044     return OHOS::ERR_OK;
3045 }
3046 
RunAsCleanBundleCacheFilesAutomaticCommand()3047 ErrCode BundleTestTool::RunAsCleanBundleCacheFilesAutomaticCommand()
3048 {
3049     ErrCode result = OHOS::ERR_OK;
3050     int counter = 0;
3051     std::string commandName = "cleanBundleCacheFilesAutomatic";
3052     uint64_t cacheSize;
3053     APP_LOGI("RunAsCleanBundleCacheFilesAutomaticCommand is start");
3054     while (true) {
3055         counter++;
3056         int option = getopt_long(argc_, argv_, SHORT_OPTIONS_AUTO_CLEAN_CACHE.c_str(),
3057             LONG_OPTIONS_AUTO_CLEAN_CACHE, nullptr);
3058         APP_LOGI("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3059         if (optind < 0 || optind > argc_) {
3060             return OHOS::ERR_INVALID_VALUE;
3061         }
3062         if (option == -1) {
3063             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3064                 APP_LOGE("bundle_test_tool getRule with no option.");
3065                 resultReceiver_.append(HELP_MSG_NO_AUTO_CLEAN_CACHE_OPTION);
3066                 return OHOS::ERR_INVALID_VALUE;
3067             }
3068             break;
3069         }
3070         result = CheckCleanBundleCacheFilesAutomaticOption(option, commandName, cacheSize);
3071         if (result != OHOS::ERR_OK) {
3072             resultReceiver_.append(HELP_MSG_AUTO_CLEAN_CACHE_RULE);
3073             return OHOS::ERR_INVALID_VALUE;
3074         }
3075     }
3076 
3077     ErrCode res = bundleMgrProxy_->CleanBundleCacheFilesAutomatic(cacheSize);
3078     if (res == ERR_OK) {
3079         resultReceiver_.append("clean fixed size cache successfully\n");
3080     } else {
3081         resultReceiver_.append("clean fixed size cache failed, errCode is "+ std::to_string(res) + "\n");
3082         APP_LOGE("CleanBundleCacheFilesAutomatic failed, result: %{public}d", res);
3083         return res;
3084     }
3085 
3086     return res;
3087 }
3088 
RunAsGetContinueBundleName()3089 ErrCode BundleTestTool::RunAsGetContinueBundleName()
3090 {
3091     APP_LOGD("RunAsGetContinueBundleName start");
3092     std::string bundleName;
3093     int32_t userId = Constants::UNSPECIFIED_USERID;
3094     int32_t appIndex;
3095     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3096     if (result != OHOS::ERR_OK) {
3097         resultReceiver_.append("RunAsGetContinueBundleName erro!!");
3098     } else {
3099         if (userId == Constants::UNSPECIFIED_USERID) {
3100             int32_t mockUid = 20010099;
3101             // Mock the current tool uid, the current default user must be executed under 100.
3102             int setResult = setuid(mockUid);
3103             APP_LOGD("Set uid result: %{public}d", setResult);
3104         }
3105 
3106         std::string msg;
3107         result = GetContinueBundleName(bundleName, userId, msg);
3108         APP_LOGD("Get continue bundle result %{public}d", result);
3109         if (result == OHOS::ERR_OK) {
3110             resultReceiver_.append(msg);
3111             return ERR_OK;
3112         } else {
3113             APP_LOGE("Get continue bundle name error: %{public}d", result);
3114             std::string err("Get continue bundle name error!");
3115             resultReceiver_.append(err);
3116         }
3117     }
3118     return OHOS::ERR_INVALID_VALUE;
3119 }
3120 
GetContinueBundleName(const std::string & bundleName,int32_t userId,std::string & msg)3121 ErrCode BundleTestTool::GetContinueBundleName(const std::string &bundleName, int32_t userId, std::string& msg)
3122 {
3123     if (bundleMgrProxy_ == nullptr) {
3124         APP_LOGE("Bundle mgr proxy is nullptr");
3125         return OHOS::ERR_INVALID_VALUE;
3126     }
3127     std::vector<std::string> continueBundleName;
3128     auto ret = bundleMgrProxy_->GetContinueBundleNames(bundleName, continueBundleName, userId);
3129     APP_LOGD("Get continue bundle names result: %{public}d", ret);
3130     if (ret == OHOS::ERR_OK) {
3131         msg = "continueBundleNameList:\n{\n";
3132         for (const auto &name : continueBundleName) {
3133             msg +="     ";
3134             msg += name;
3135             msg += "\n";
3136         }
3137         msg += "}\n";
3138         return ERR_OK;
3139     }
3140     return ret;
3141 }
3142 
RunAsDeployQuickFix()3143 ErrCode BundleTestTool::RunAsDeployQuickFix()
3144 {
3145     int32_t result = OHOS::ERR_OK;
3146     int32_t counter = 0;
3147     int32_t index = 0;
3148     std::vector<std::string> quickFixPaths;
3149     int32_t isDebug = 0;
3150     while (true) {
3151         counter++;
3152         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3153         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3154         if (optind < 0 || optind > argc_) {
3155             return OHOS::ERR_INVALID_VALUE;
3156         }
3157 
3158         if (option == -1 || option == '?') {
3159             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3160                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3161                 result = OHOS::ERR_INVALID_VALUE;
3162                 break;
3163             }
3164             if ((optopt == 'p') || (optopt == 'd')) {
3165                 // 'bm deployQuickFix --patch-path' with no argument
3166                 // 'bm deployQuickFix -d' with no argument
3167                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3168                 result = OHOS::ERR_INVALID_VALUE;
3169                 break;
3170             }
3171             break;
3172         }
3173 
3174         if (option == 'p') {
3175             APP_LOGD("'bm deployQuickFix -p %{public}s'", argv_[optind - 1]);
3176             quickFixPaths.emplace_back(optarg);
3177             index = optind;
3178             continue;
3179         }
3180         if ((option == 'd') && OHOS::StrToInt(optarg, isDebug)) {
3181             APP_LOGD("'bm deployQuickFix -d %{public}s'", argv_[optind - 1]);
3182             continue;
3183         }
3184 
3185         result = OHOS::ERR_INVALID_VALUE;
3186         break;
3187     }
3188 
3189     if (result != OHOS::ERR_OK || GetQuickFixPath(index, quickFixPaths) != OHOS::ERR_OK) {
3190         resultReceiver_.append(HELP_MSG_DEPLOY_QUICK_FIX);
3191         return result;
3192     }
3193 
3194     std::shared_ptr<QuickFixResult> deployRes = nullptr;
3195     result = DeployQuickFix(quickFixPaths, deployRes, isDebug != 0);
3196     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DEPLOY_QUICK_FIX_OK : STRING_DEPLOY_QUICK_FIX_NG;
3197     resultReceiver_ += GetResMsg(result, deployRes);
3198 
3199     return result;
3200 }
3201 
GetQuickFixPath(int32_t index,std::vector<std::string> & quickFixPaths) const3202 ErrCode BundleTestTool::GetQuickFixPath(int32_t index, std::vector<std::string>& quickFixPaths) const
3203 {
3204     APP_LOGI("GetQuickFixPath start");
3205     for (; index < argc_ && index >= INDEX_OFFSET; ++index) {
3206         if (argList_[index - INDEX_OFFSET] == "-p" || argList_[index - INDEX_OFFSET] == "--patch-path") {
3207             break;
3208         }
3209 
3210         std::string innerPath = argList_[index - INDEX_OFFSET];
3211         if (innerPath.empty() || innerPath == "-p" || innerPath == "--patch-path") {
3212             quickFixPaths.clear();
3213             return OHOS::ERR_INVALID_VALUE;
3214         }
3215         APP_LOGD("GetQuickFixPath is %{public}s'", innerPath.c_str());
3216         quickFixPaths.emplace_back(innerPath);
3217     }
3218     return OHOS::ERR_OK;
3219 }
3220 
RunAsSwitchQuickFix()3221 ErrCode BundleTestTool::RunAsSwitchQuickFix()
3222 {
3223     int32_t result = OHOS::ERR_OK;
3224     int32_t counter = 0;
3225     int32_t enable = -1;
3226     std::string bundleName;
3227     while (true) {
3228         counter++;
3229         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3230         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3231         if (optind < 0 || optind > argc_) {
3232             return OHOS::ERR_INVALID_VALUE;
3233         }
3234 
3235         if (option == -1 || option == '?') {
3236             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3237                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3238                 result = OHOS::ERR_INVALID_VALUE;
3239                 break;
3240             }
3241             if (optopt == 'n' || optopt == 'e') {
3242                 // 'bm switchQuickFix -n -e' with no argument
3243                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3244                 result = OHOS::ERR_INVALID_VALUE;
3245                 break;
3246             }
3247             break;
3248         }
3249 
3250         if (option == 'n') {
3251             APP_LOGD("'bm switchQuickFix -n %{public}s'", argv_[optind - 1]);
3252             bundleName = optarg;
3253             continue;
3254         }
3255         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
3256             APP_LOGD("'bm switchQuickFix -e %{public}s'", argv_[optind - 1]);
3257             continue;
3258         }
3259         result = OHOS::ERR_INVALID_VALUE;
3260         break;
3261     }
3262 
3263     if ((result != OHOS::ERR_OK) || (enable < 0) || (enable > 1)) {
3264         resultReceiver_.append(HELP_MSG_SWITCH_QUICK_FIX);
3265         return result;
3266     }
3267     std::shared_ptr<QuickFixResult> switchRes = nullptr;
3268     result = SwitchQuickFix(bundleName, enable, switchRes);
3269     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_SWITCH_QUICK_FIX_OK : STRING_SWITCH_QUICK_FIX_NG;
3270     resultReceiver_ += GetResMsg(result, switchRes);
3271 
3272     return result;
3273 }
3274 
RunAsDeleteQuickFix()3275 ErrCode BundleTestTool::RunAsDeleteQuickFix()
3276 {
3277     int32_t result = OHOS::ERR_OK;
3278     int32_t counter = 0;
3279     std::string bundleName;
3280     while (true) {
3281         counter++;
3282         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUICK_FIX.c_str(), LONG_OPTIONS_QUICK_FIX, nullptr);
3283         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3284         if (optind < 0 || optind > argc_) {
3285             return OHOS::ERR_INVALID_VALUE;
3286         }
3287 
3288         if (option == -1 || option == '?') {
3289             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3290                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3291                 result = OHOS::ERR_INVALID_VALUE;
3292                 break;
3293             }
3294             if (optopt == 'n') {
3295                 // 'bm deleteQuickFix -n' with no argument
3296                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3297                 result = OHOS::ERR_INVALID_VALUE;
3298                 break;
3299             }
3300             break;
3301         }
3302 
3303         if (option == 'n') {
3304             APP_LOGD("'bm deleteQuickFix -n %{public}s'", argv_[optind - 1]);
3305             bundleName = optarg;
3306             continue;
3307         }
3308         result = OHOS::ERR_INVALID_VALUE;
3309         break;
3310     }
3311 
3312     if (result != OHOS::ERR_OK) {
3313         resultReceiver_.append(HELP_MSG_DELETE_QUICK_FIX);
3314         return result;
3315     }
3316     std::shared_ptr<QuickFixResult> deleteRes = nullptr;
3317     result = DeleteQuickFix(bundleName, deleteRes);
3318     resultReceiver_ = (result == OHOS::ERR_OK) ? STRING_DELETE_QUICK_FIX_OK : STRING_DELETE_QUICK_FIX_NG;
3319     resultReceiver_ += GetResMsg(result, deleteRes);
3320 
3321     return result;
3322 }
3323 
DeployQuickFix(const std::vector<std::string> & quickFixPaths,std::shared_ptr<QuickFixResult> & quickFixRes,bool isDebug)3324 ErrCode BundleTestTool::DeployQuickFix(const std::vector<std::string> &quickFixPaths,
3325     std::shared_ptr<QuickFixResult> &quickFixRes, bool isDebug)
3326 {
3327 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3328     std::set<std::string> realPathSet;
3329     for (const auto &quickFixPath : quickFixPaths) {
3330         std::string realPath;
3331         if (!PathToRealPath(quickFixPath, realPath)) {
3332             APP_LOGW("quickFixPath %{public}s is invalid", quickFixPath.c_str());
3333             continue;
3334         }
3335         APP_LOGD("realPath is %{public}s", realPath.c_str());
3336         realPathSet.insert(realPath);
3337     }
3338     std::vector<std::string> pathVec(realPathSet.begin(), realPathSet.end());
3339 
3340     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3341     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3342         APP_LOGE("callback or bundleMgrProxy is null");
3343         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3344     }
3345     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3346     if (recipient == nullptr) {
3347         APP_LOGE("recipient is null");
3348         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3349     }
3350     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3351     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3352     if (quickFixProxy == nullptr) {
3353         APP_LOGE("quickFixProxy is null");
3354         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3355     }
3356     std::vector<std::string> destFiles;
3357     auto res = quickFixProxy->CopyFiles(pathVec, destFiles);
3358     if (res != ERR_OK) {
3359         APP_LOGE("Copy files failed with %{public}d.", res);
3360         return res;
3361     }
3362     res = quickFixProxy->DeployQuickFix(destFiles, callback, isDebug);
3363     if (res != ERR_OK) {
3364         APP_LOGE("DeployQuickFix failed");
3365         return res;
3366     }
3367 
3368     return callback->GetResultCode(quickFixRes);
3369 #else
3370     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3371 #endif
3372 }
3373 
SwitchQuickFix(const std::string & bundleName,int32_t enable,std::shared_ptr<QuickFixResult> & quickFixRes)3374 ErrCode BundleTestTool::SwitchQuickFix(const std::string &bundleName, int32_t enable,
3375     std::shared_ptr<QuickFixResult> &quickFixRes)
3376 {
3377     APP_LOGD("SwitchQuickFix bundleName: %{public}s, enable: %{public}d", bundleName.c_str(), enable);
3378 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3379     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3380     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3381         APP_LOGE("callback or bundleMgrProxy is null");
3382         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3383     }
3384     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3385     if (recipient == nullptr) {
3386         APP_LOGE("recipient is null");
3387         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3388     }
3389     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3390     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3391     if (quickFixProxy == nullptr) {
3392         APP_LOGE("quickFixProxy is null");
3393         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3394     }
3395     bool enableFlag = (enable == 0) ? false : true;
3396     auto res = quickFixProxy->SwitchQuickFix(bundleName, enableFlag, callback);
3397     if (res != ERR_OK) {
3398         APP_LOGE("SwitchQuickFix failed");
3399         return res;
3400     }
3401     return callback->GetResultCode(quickFixRes);
3402 #else
3403     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3404 #endif
3405 }
3406 
DeleteQuickFix(const std::string & bundleName,std::shared_ptr<QuickFixResult> & quickFixRes)3407 ErrCode BundleTestTool::DeleteQuickFix(const std::string &bundleName,
3408     std::shared_ptr<QuickFixResult> &quickFixRes)
3409 {
3410     APP_LOGD("DeleteQuickFix bundleName: %{public}s", bundleName.c_str());
3411 #ifdef BUNDLE_FRAMEWORK_QUICK_FIX
3412     sptr<QuickFixStatusCallbackHostlmpl> callback(new (std::nothrow) QuickFixStatusCallbackHostlmpl());
3413     if (callback == nullptr || bundleMgrProxy_ == nullptr) {
3414         APP_LOGE("callback or bundleMgrProxy is null");
3415         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3416     }
3417     sptr<BundleDeathRecipient> recipient(new (std::nothrow) BundleDeathRecipient(nullptr, callback));
3418     if (recipient == nullptr) {
3419         APP_LOGE("recipient is null");
3420         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3421     }
3422     bundleMgrProxy_->AsObject()->AddDeathRecipient(recipient);
3423     auto quickFixProxy = bundleMgrProxy_->GetQuickFixManagerProxy();
3424     if (quickFixProxy == nullptr) {
3425         APP_LOGE("quickFixProxy is null");
3426         return ERR_BUNDLEMANAGER_QUICK_FIX_INTERNAL_ERROR;
3427     }
3428     auto res = quickFixProxy->DeleteQuickFix(bundleName, callback);
3429     if (res != ERR_OK) {
3430         APP_LOGE("DeleteQuickFix failed");
3431         return res;
3432     }
3433     return callback->GetResultCode(quickFixRes);
3434 #else
3435     return ERR_BUNDLEMANAGER_FEATURE_IS_NOT_SUPPORTED;
3436 #endif
3437 }
3438 
GetResMsg(int32_t code)3439 std::string BundleTestTool::GetResMsg(int32_t code)
3440 {
3441     std::unordered_map<int32_t, std::string> quickFixMsgMap;
3442     CreateQuickFixMsgMap(quickFixMsgMap);
3443     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
3444         return quickFixMsgMap.at(code);
3445     }
3446     return MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
3447 }
3448 
GetResMsg(int32_t code,const std::shared_ptr<QuickFixResult> & quickFixRes)3449 std::string BundleTestTool::GetResMsg(int32_t code, const std::shared_ptr<QuickFixResult> &quickFixRes)
3450 {
3451     std::string resMsg;
3452     std::unordered_map<int32_t, std::string> quickFixMsgMap;
3453     CreateQuickFixMsgMap(quickFixMsgMap);
3454     if (quickFixMsgMap.find(code) != quickFixMsgMap.end()) {
3455         resMsg += quickFixMsgMap.at(code);
3456     } else {
3457         resMsg += MSG_ERR_BUNDLEMANAGER_QUICK_FIX_UNKOWN;
3458     }
3459     if (quickFixRes != nullptr) {
3460         resMsg += quickFixRes->ToString() + "\n";
3461     }
3462     return resMsg;
3463 }
3464 
RunAsSetDebugMode()3465 ErrCode BundleTestTool::RunAsSetDebugMode()
3466 {
3467     int32_t result = OHOS::ERR_OK;
3468     int32_t counter = 0;
3469     int32_t enable = -1;
3470     while (true) {
3471         counter++;
3472         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_DEBUG_MODE.c_str(), LONG_OPTIONS_DEBUG_MODE, nullptr);
3473         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3474         if (optind < 0 || optind > argc_) {
3475             return OHOS::ERR_INVALID_VALUE;
3476         }
3477 
3478         if (option == -1 || option == '?') {
3479             if (counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0) {
3480                 resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3481                 result = OHOS::ERR_INVALID_VALUE;
3482                 break;
3483             }
3484             if (optopt == 'e') {
3485                 // 'bundle_test_tool setDebugMode -e' with no argument
3486                 resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3487                 result = OHOS::ERR_INVALID_VALUE;
3488                 break;
3489             }
3490             break;
3491         }
3492 
3493         if (option == 'e' && OHOS::StrToInt(optarg, enable)) {
3494             APP_LOGD("'bundle_test_tool setDebugMode -e %{public}s'", argv_[optind - 1]);
3495             continue;
3496         }
3497         result = OHOS::ERR_INVALID_VALUE;
3498         break;
3499     }
3500 
3501     if (result != OHOS::ERR_OK) {
3502         resultReceiver_.append(HELP_MSG_SET_DEBUG_MODE);
3503         return result;
3504     }
3505     ErrCode setResult = SetDebugMode(enable);
3506     if (setResult == OHOS::ERR_OK) {
3507         resultReceiver_ = STRING_SET_DEBUG_MODE_OK;
3508     } else {
3509         resultReceiver_ = STRING_SET_DEBUG_MODE_NG + GetResMsg(setResult);
3510     }
3511     return setResult;
3512 }
3513 
SetDebugMode(int32_t debugMode)3514 ErrCode BundleTestTool::SetDebugMode(int32_t debugMode)
3515 {
3516     if (debugMode != 0 && debugMode != 1) {
3517         APP_LOGE("SetDebugMode param is invalid");
3518         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INVALID_PARAM;
3519     }
3520     bool enable = debugMode == 0 ? false : true;
3521     if (bundleMgrProxy_ == nullptr) {
3522         APP_LOGE("bundleMgrProxy_ is nullptr");
3523         return ERR_BUNDLEMANAGER_SET_DEBUG_MODE_INTERNAL_ERROR;
3524     }
3525     return bundleMgrProxy_->SetDebugMode(enable);
3526 }
3527 
BundleNameAndUserIdCommonFunc(std::string & bundleName,int32_t & userId,int32_t & appIndex)3528 ErrCode BundleTestTool::BundleNameAndUserIdCommonFunc(std::string &bundleName, int32_t &userId, int32_t &appIndex)
3529 {
3530     int32_t result = OHOS::ERR_OK;
3531     int32_t counter = 0;
3532     userId = Constants::UNSPECIFIED_USERID;
3533     while (true) {
3534         counter++;
3535         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLE_STATS.c_str(),
3536             LONG_OPTIONS_GET_BUNDLE_STATS, nullptr);
3537         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3538         if (optind < 0 || optind > argc_) {
3539             return OHOS::ERR_INVALID_VALUE;
3540         }
3541         if (option == -1) {
3542             if (counter == 1) {
3543                 // When scanning the first argument
3544                 if (strcmp(argv_[optind], cmd_.c_str()) == 0) {
3545                     resultReceiver_.append(HELP_MSG_NO_OPTION + "\n");
3546                     result = OHOS::ERR_INVALID_VALUE;
3547                 }
3548             }
3549             break;
3550         }
3551 
3552         if (option == '?') {
3553             switch (optopt) {
3554                 case 'n': {
3555                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3556                     result = OHOS::ERR_INVALID_VALUE;
3557                     break;
3558                 }
3559                 case 'u': {
3560                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3561                     result = OHOS::ERR_INVALID_VALUE;
3562                     break;
3563                 }
3564                 case 'a': {
3565                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3566                     result = OHOS::ERR_INVALID_VALUE;
3567                     break;
3568                 }
3569                 default: {
3570                     std::string unknownOption = "";
3571                     std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
3572                     resultReceiver_.append(unknownOptionMsg);
3573                     result = OHOS::ERR_INVALID_VALUE;
3574                     break;
3575                 }
3576             }
3577             break;
3578         }
3579 
3580         switch (option) {
3581             case 'h': {
3582                 result = OHOS::ERR_INVALID_VALUE;
3583                 break;
3584             }
3585             case 'n': {
3586                 bundleName = optarg;
3587                 break;
3588             }
3589             case 'u': {
3590                 if (!OHOS::StrToInt(optarg, userId) || userId < 0) {
3591                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3592                     return OHOS::ERR_INVALID_VALUE;
3593                 }
3594                 break;
3595             }
3596             case 'a': {
3597                 if (!OHOS::StrToInt(optarg, appIndex) || (appIndex < 0 || appIndex > INITIAL_SANDBOX_APP_INDEX)) {
3598                     resultReceiver_.append(STRING_REQUIRE_CORRECT_VALUE);
3599                     return OHOS::ERR_INVALID_VALUE;
3600                 }
3601                 break;
3602             }
3603             default: {
3604                 result = OHOS::ERR_INVALID_VALUE;
3605                 break;
3606             }
3607         }
3608     }
3609 
3610     if (result == OHOS::ERR_OK) {
3611         if (resultReceiver_ == "" && bundleName.size() == 0) {
3612             resultReceiver_.append(HELP_MSG_NO_BUNDLE_NAME_OPTION + "\n");
3613             result = OHOS::ERR_INVALID_VALUE;
3614         }
3615     }
3616     return result;
3617 }
3618 
RunAsGetBundleStats()3619 ErrCode BundleTestTool::RunAsGetBundleStats()
3620 {
3621     std::string bundleName;
3622     int32_t userId;
3623     int32_t appIndex = 0;
3624     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3625     if (result != OHOS::ERR_OK) {
3626         resultReceiver_.append(HELP_MSG_GET_BUNDLE_STATS);
3627     } else {
3628         std::string msg;
3629         bool ret = GetBundleStats(bundleName, userId, msg, appIndex);
3630         if (ret) {
3631             resultReceiver_ = STRING_GET_BUNDLE_STATS_OK + msg;
3632         } else {
3633             resultReceiver_ = STRING_GET_BUNDLE_STATS_NG + "\n";
3634         }
3635     }
3636 
3637     return result;
3638 }
3639 
GetBundleStats(const std::string & bundleName,int32_t userId,std::string & msg,int32_t appIndex)3640 bool BundleTestTool::GetBundleStats(const std::string &bundleName, int32_t userId,
3641     std::string& msg, int32_t appIndex)
3642 {
3643     if (bundleMgrProxy_ == nullptr) {
3644         APP_LOGE("bundleMgrProxy_ is nullptr");
3645         return false;
3646     }
3647     userId = BundleCommandCommon::GetCurrentUserId(userId);
3648     std::vector<std::int64_t> bundleStats;
3649     bool ret = bundleMgrProxy_->GetBundleStats(bundleName, userId, bundleStats, appIndex);
3650     if (ret) {
3651         for (size_t index = 0; index < bundleStats.size(); ++index) {
3652             msg += GET_BUNDLE_STATS_ARRAY[index] + std::to_string(bundleStats[index]) + "\n";
3653         }
3654     }
3655     return ret;
3656 }
3657 
RunAsGetAllBundleCacheStat()3658 ErrCode BundleTestTool::RunAsGetAllBundleCacheStat()
3659 {
3660     APP_LOGI("RunAsGetAllBundleCacheStat start");
3661     std::string commandName = "getAllBundleCacheStat";
3662     int32_t result = OHOS::ERR_OK;
3663     int32_t counter = 0;
3664     std::string name = "";
3665     std::string msg;
3666     int uid = 0;
3667     while (counter <= 1) {
3668         counter++;
3669         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT.c_str(),
3670             LONG_OPTIONS_GET_ALL_BUNDLE_CACHE_STAT, nullptr);
3671         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3672         if (optind < 0 || optind > argc_) {
3673             return OHOS::ERR_INVALID_VALUE;
3674         }
3675         if (option == -1) {
3676             // When scanning the first argument
3677             if ((counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3678                 msg = "with no option, set uid: 0";
3679                 resultReceiver_.append(msg + "\n");
3680                 setuid(uid);
3681                 break;
3682             }
3683             if (counter > 1) {
3684                 msg = "get uid: " + std::to_string(uid);
3685                 resultReceiver_.append(msg + "\n");
3686                 break;
3687             }
3688         }
3689         int temp = 0;
3690         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
3691             ? OHOS::ERR_INVALID_VALUE : result;
3692         uid = option == 'u' ? temp : uid;
3693         setuid(uid);
3694     }
3695     if (result != OHOS::ERR_OK) {
3696         resultReceiver_.append(HELP_MSG_GET_ALL_BUNDLE_CACHE_STAT);
3697     } else {
3698         msg = "";
3699         result = GetAllBundleCacheStat(msg);
3700         if (ERR_OK == result) {
3701             resultReceiver_.append(STRING_GET_ALL_BUNDLE_CACHE_STAT_OK + msg);
3702         } else {
3703             resultReceiver_.append(STRING_GET_ALL_BUNDLE_CACHE_STAT_NG + msg + "\n");
3704         }
3705     }
3706     APP_LOGI("RunAsGetAllBundleCacheStat end");
3707     return result;
3708 }
3709 
GetAllBundleCacheStat(std::string & msg)3710 ErrCode BundleTestTool::GetAllBundleCacheStat(std::string& msg)
3711 {
3712     if (bundleMgrProxy_ == nullptr) {
3713         APP_LOGE("bundleMgrProxy_ is nullptr");
3714         return OHOS::ERR_INVALID_VALUE;
3715     }
3716     sptr<ProcessCacheCallbackImpl> processCacheCallBack(new (std::nothrow) ProcessCacheCallbackImpl());
3717     if (processCacheCallBack == nullptr) {
3718         APP_LOGE("processCacheCallBack is null");
3719         return OHOS::ERR_INVALID_VALUE;
3720     }
3721     ErrCode ret = bundleMgrProxy_->GetAllBundleCacheStat(processCacheCallBack);
3722     uint64_t cacheSize = 0;
3723     if (ret ==ERR_OK) {
3724         msg += "clean exec wait \n";
3725         if (processCacheCallBack->WaitForStatCompletion()) {
3726             cacheSize = processCacheCallBack->GetCacheStat();
3727         } else {
3728             msg += "clean exec timeout \n";
3729         }
3730     }
3731     msg += "clean exec end \n";
3732     if (ret == ERR_OK) {
3733         msg += "AllBundleCacheStat:" + std::to_string(cacheSize) + "\n";
3734     } else {
3735         msg += "error code:" + std::to_string(ret) + "\n";
3736     }
3737     return ret;
3738 }
3739 
RunAsCleanAllBundleCache()3740 ErrCode BundleTestTool::RunAsCleanAllBundleCache()
3741 {
3742     APP_LOGI("RunAsCleanAllBundleCache start");
3743     std::string commandName = "cleanAllBundleCache";
3744     int32_t result = OHOS::ERR_OK;
3745     int32_t counter = 0;
3746     std::string name = "";
3747     std::string msg;
3748     int uid = 0;
3749     while (counter <= 1) {
3750         counter++;
3751         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_CLEAN_ALL_BUNDLE_CACHE.c_str(),
3752             LONG_OPTIONS_CLEAN_ALL_BUNDLE_CACHE, nullptr);
3753         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3754         if (optind < 0 || optind > argc_) {
3755             return OHOS::ERR_INVALID_VALUE;
3756         }
3757         if (option == -1) {
3758             // When scanning the first argument
3759             if ((counter == 1 && strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3760                 msg = "with no option, set uid: 0";
3761                 resultReceiver_.append(msg + "\n");
3762                 setuid(uid);
3763                 break;
3764             }
3765             if (counter > 1) {
3766                 msg = "get uid: " + std::to_string(uid);
3767                 resultReceiver_.append(msg + "\n");
3768                 break;
3769             }
3770         }
3771         int temp = 0;
3772         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
3773             ? OHOS::ERR_INVALID_VALUE : result;
3774         uid = option == 'u' ? temp : uid;
3775         setuid(uid);
3776     }
3777     if (result != OHOS::ERR_OK) {
3778         resultReceiver_.append(HELP_MSG_CLEAN_ALL_BUNDLE_CACHE);
3779     } else {
3780         msg = "";
3781         result = CleanAllBundleCache(msg);
3782         if (ERR_OK == result) {
3783             resultReceiver_.append(STRING_CLEAN_ALL_BUNDLE_CACHE_OK + msg);
3784         } else {
3785             resultReceiver_.append(STRING_CLEAN_ALL_BUNDLE_CACHE_NG + msg + "\n");
3786         }
3787     }
3788     APP_LOGI("RunAsCleanAllBundleCache end");
3789     return result;
3790 }
3791 
CleanAllBundleCache(std::string & msg)3792 ErrCode BundleTestTool::CleanAllBundleCache(std::string& msg)
3793 {
3794     if (bundleMgrProxy_ == nullptr) {
3795         APP_LOGE("bundleMgrProxy_ is nullptr");
3796         return OHOS::ERR_INVALID_VALUE;
3797     }
3798     sptr<ProcessCacheCallbackImpl> processCacheCallBack(new (std::nothrow) ProcessCacheCallbackImpl());
3799     if (processCacheCallBack == nullptr) {
3800         APP_LOGE("processCacheCallBack is null");
3801         return OHOS::ERR_INVALID_VALUE;
3802     }
3803 
3804     ErrCode ret = bundleMgrProxy_->CleanAllBundleCache(processCacheCallBack);
3805     int32_t cleanRet = 0;
3806     std::string callbackMsg = "";
3807     if (ret ==ERR_OK) {
3808         callbackMsg += "clean exec wait \n";
3809         if (processCacheCallBack->WaitForCleanCompletion()) {
3810             cleanRet = processCacheCallBack->GetDelRet();
3811         } else {
3812             callbackMsg += "clean exec timeout \n";
3813             cleanRet = -1;
3814         }
3815     }
3816     callbackMsg += "clean exec end \n";
3817     if (ret != ERR_OK || cleanRet != ERR_OK) {
3818         callbackMsg += "return code:" + std::to_string(ret) + " cleanRet code:" + std::to_string(cleanRet) + "\n";
3819         msg = callbackMsg;
3820         return OHOS::ERR_INVALID_VALUE;
3821     }
3822     return ERR_OK;
3823 }
3824 
RunAsGetAppProvisionInfo()3825 ErrCode BundleTestTool::RunAsGetAppProvisionInfo()
3826 {
3827     std::string bundleName;
3828     int32_t userId;
3829     int32_t appIndex = 0;
3830     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
3831     if (result != OHOS::ERR_OK) {
3832         resultReceiver_.append(HELP_MSG_GET_APP_PROVISION_INFO);
3833     } else {
3834         std::string msg;
3835         result = GetAppProvisionInfo(bundleName, userId, msg);
3836         if (result == OHOS::ERR_OK) {
3837             resultReceiver_ = STRING_GET_APP_PROVISION_INFO_OK + msg;
3838         } else {
3839             resultReceiver_ = STRING_GET_APP_PROVISION_INFO_NG + "\n";
3840         }
3841     }
3842 
3843     return result;
3844 }
3845 
GetAppProvisionInfo(const std::string & bundleName,int32_t userId,std::string & msg)3846 ErrCode BundleTestTool::GetAppProvisionInfo(const std::string &bundleName,
3847     int32_t userId, std::string& msg)
3848 {
3849     if (bundleMgrProxy_ == nullptr) {
3850         APP_LOGE("bundleMgrProxy_ is nullptr");
3851         return OHOS::ERR_INVALID_VALUE;
3852     }
3853     userId = BundleCommandCommon::GetCurrentUserId(userId);
3854     AppProvisionInfo info;
3855     auto ret = bundleMgrProxy_->GetAppProvisionInfo(bundleName, userId, info);
3856     if (ret == ERR_OK) {
3857         msg = "{\n";
3858         msg += "    versionCode: " + std::to_string(info.versionCode) + "\n";
3859         msg += "    versionName: " + info.versionName+ "\n";
3860         msg += "    uuid: " + info.uuid + "\n";
3861         msg += "    type: " + info.type + "\n";
3862         msg += "    appDistributionType: " + info.appDistributionType + "\n";
3863         msg += "    developerId: " + info.developerId + "\n";
3864         msg += "    certificate: " + info.certificate + "\n";
3865         msg += "    apl: " + info.apl + "\n";
3866         msg += "    issuer: " + info.issuer + "\n";
3867         msg += "    validity: {\n";
3868         msg += "        notBefore: " + std::to_string(info.validity.notBefore) + "\n";
3869         msg += "        notAfter: " + std::to_string(info.validity.notAfter) + "\n";
3870         msg += "    }\n";
3871         msg += "    appServiceCapabilities: " + info.appServiceCapabilities + "\n";
3872         msg += "}\n";
3873     }
3874     return ret;
3875 }
3876 
RunAsGetDistributedBundleName()3877 ErrCode BundleTestTool::RunAsGetDistributedBundleName()
3878 {
3879     ErrCode result;
3880     std::string networkId;
3881     int32_t counter = 0;
3882     int32_t accessTokenId = 0;
3883     while (true) {
3884         counter++;
3885         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME.c_str(),
3886             LONG_OPTIONS_GET_DISTRIBUTED_BUNDLE_NAME, nullptr);
3887         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
3888         if (optind < 0 || optind > argc_) {
3889             return OHOS::ERR_INVALID_VALUE;
3890         }
3891         if (option == -1) {
3892             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
3893                 resultReceiver_.append(HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION);
3894                 return OHOS::ERR_INVALID_VALUE;
3895             }
3896             break;
3897         }
3898         result = CheckGetDistributedBundleNameCorrectOption(option, GET_DISTRIBUTED_BUNDLE_NAME_COMMAND_NAME,
3899             networkId, accessTokenId);
3900         if (result != OHOS::ERR_OK) {
3901             resultReceiver_.append(HELP_MSG_GET_DISTRIBUTED_BUNDLE_NAME);
3902             return OHOS::ERR_INVALID_VALUE;
3903         }
3904     }
3905     if (accessTokenId == 0 || networkId.size() == 0) {
3906         resultReceiver_.append(HELP_MSG_NO_GET_DISTRIBUTED_BUNDLE_NAME_OPTION);
3907         return OHOS::ERR_INVALID_VALUE;
3908     }
3909     std::string msg;
3910     result = GetDistributedBundleName(networkId, accessTokenId, msg);
3911     if (result == OHOS::ERR_OK) {
3912         resultReceiver_ = STRING_GET_DISTRIBUTED_BUNDLE_NAME_OK + msg;
3913     } else {
3914         resultReceiver_ = STRING_GET_DISTRIBUTED_BUNDLE_NAME_NG + "\n";
3915         APP_LOGE("RunAsGetDistributedBundleName fail result %{public}d.", result);
3916     }
3917     return result;
3918 }
3919 
CheckGetDistributedBundleNameCorrectOption(int32_t option,const std::string & commandName,std::string & networkId,int32_t & accessTokenId)3920 ErrCode BundleTestTool::CheckGetDistributedBundleNameCorrectOption(int32_t option, const std::string &commandName,
3921     std::string &networkId, int32_t &accessTokenId)
3922 {
3923     ErrCode result = OHOS::ERR_OK;
3924     switch (option) {
3925         case 'h': {
3926             result = OHOS::ERR_INVALID_VALUE;
3927             break;
3928         }
3929         case 'n': {
3930             networkId = optarg;
3931             if (networkId.size() == 0) {
3932                 return OHOS::ERR_INVALID_VALUE;
3933             }
3934             break;
3935         }
3936         case 'a': {
3937             if (!OHOS::StrToInt(optarg, accessTokenId) || accessTokenId < 0) {
3938                 return OHOS::ERR_INVALID_VALUE;
3939             }
3940             break;
3941         }
3942         default: {
3943             result = OHOS::ERR_INVALID_VALUE;
3944             break;
3945         }
3946     }
3947     return result;
3948 }
3949 
GetDistributedBundleName(const std::string & networkId,int32_t accessTokenId,std::string & msg)3950 ErrCode BundleTestTool::GetDistributedBundleName(const std::string &networkId,
3951     int32_t accessTokenId, std::string& msg)
3952 {
3953 #ifdef DISTRIBUTED_BUNDLE_FRAMEWORK
3954     if (distributedBmsProxy_ == nullptr) {
3955         APP_LOGE("distributedBmsProxy_ is nullptr");
3956         return OHOS::ERR_INVALID_VALUE;
3957     }
3958     std::string bundleName;
3959     auto ret = distributedBmsProxy_->GetDistributedBundleName(networkId, accessTokenId, bundleName);
3960     if (ret == OHOS::NO_ERROR) {
3961         msg = "\n";
3962         if (bundleName.size() == 0) {
3963             msg += "no match found \n";
3964         } else {
3965             msg += bundleName + "\n";
3966         }
3967         msg += "\n";
3968     } else {
3969         APP_LOGE("distributedBmsProxy_ GetDistributedBundleName fail errcode %{public}d.", ret);
3970         return OHOS::ERR_INVALID_VALUE;
3971     }
3972     return OHOS::ERR_OK;
3973 #else
3974     return OHOS::ERR_INVALID_VALUE;
3975 #endif
3976 }
3977 
ParseEventCallbackOptions(bool & onlyUnregister,int32_t & uid)3978 bool BundleTestTool::ParseEventCallbackOptions(bool &onlyUnregister, int32_t &uid)
3979 {
3980     int32_t opt;
3981     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_BUNDLE_EVENT_CALLBACK.c_str(),
3982         LONG_OPTIONS_BUNDLE_EVENT_CALLBACK, nullptr)) != -1) {
3983         switch (opt) {
3984             case 'o': {
3985                 onlyUnregister = true;
3986                 break;
3987             }
3988             case 'u': {
3989                 if (!OHOS::StrToInt(optarg, uid)) {
3990                     std::string msg = "invalid param, uid should be int";
3991                     resultReceiver_.append(msg).append(LINE_BREAK);
3992                     APP_LOGE("%{public}s", msg.c_str());
3993                     return false;
3994                 }
3995                 break;
3996             }
3997             case 'h': {
3998                 resultReceiver_.append(HELP_MSG_BUNDLE_EVENT_CALLBACK);
3999                 return false;
4000             }
4001             default: {
4002                 std::string msg = "unsupported option";
4003                 resultReceiver_.append(msg).append(LINE_BREAK);
4004                 APP_LOGE("%{public}s", msg.c_str());
4005                 return false;
4006             }
4007         }
4008     }
4009     APP_LOGI("ParseEventCallbackOptions success");
4010     return true;
4011 }
4012 
ParseResetAOTCompileStatusOptions(std::string & bundleName,std::string & moduleName,int32_t & triggerMode,int32_t & uid)4013 bool BundleTestTool::ParseResetAOTCompileStatusOptions(std::string &bundleName, std::string &moduleName,
4014     int32_t &triggerMode, int32_t &uid)
4015 {
4016     int32_t opt;
4017     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_RESET_AOT_COMPILE_StATUS.c_str(),
4018         LONG_OPTIONS_RESET_AOT_COMPILE_StATUS, nullptr)) != -1) {
4019         switch (opt) {
4020             case 'b': {
4021                 bundleName = optarg;
4022                 break;
4023             }
4024             case 'm': {
4025                 moduleName = optarg;
4026                 break;
4027             }
4028             case 't': {
4029                 if (!OHOS::StrToInt(optarg, triggerMode)) {
4030                     std::string msg = "invalid param, triggerMode should be int";
4031                     resultReceiver_.append(msg).append(LINE_BREAK);
4032                     APP_LOGE("%{public}s", msg.c_str());
4033                     return false;
4034                 }
4035                 break;
4036             }
4037             case 'u': {
4038                 if (!OHOS::StrToInt(optarg, uid)) {
4039                     std::string msg = "invalid param, uid should be int";
4040                     resultReceiver_.append(msg).append(LINE_BREAK);
4041                     APP_LOGE("%{public}s", msg.c_str());
4042                     return false;
4043                 }
4044                 break;
4045             }
4046             case 'h': {
4047                 resultReceiver_.append(HELP_MSG_RESET_AOT_COMPILE_StATUS);
4048                 return false;
4049             }
4050             default: {
4051                 std::string msg = "unsupported option";
4052                 resultReceiver_.append(msg).append(LINE_BREAK);
4053                 APP_LOGE("%{public}s", msg.c_str());
4054                 return false;
4055             }
4056         }
4057     }
4058     APP_LOGI("ParseResetAOTCompileStatusOptions success");
4059     return true;
4060 }
4061 
Sleep(int32_t seconds)4062 void BundleTestTool::Sleep(int32_t seconds)
4063 {
4064     APP_LOGI("begin to sleep %{public}d seconds", seconds);
4065     std::this_thread::sleep_for(std::chrono::seconds(seconds));
4066     APP_LOGI("sleep done");
4067 }
4068 
CallRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)4069 ErrCode BundleTestTool::CallRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)
4070 {
4071     APP_LOGI("begin to call RegisterBundleEventCallback");
4072     std::string msg;
4073     bool ret = bundleMgrProxy_->RegisterBundleEventCallback(bundleEventCallback);
4074     if (!ret) {
4075         msg = "RegisterBundleEventCallback failed";
4076         resultReceiver_.append(msg).append(LINE_BREAK);
4077         APP_LOGE("%{public}s", msg.c_str());
4078         return OHOS::ERR_INVALID_VALUE;
4079     }
4080     msg = "RegisterBundleEventCallback success";
4081     resultReceiver_.append(msg).append(LINE_BREAK);
4082     APP_LOGI("%{public}s", msg.c_str());
4083     return OHOS::ERR_OK;
4084 }
4085 
CallUnRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)4086 ErrCode BundleTestTool::CallUnRegisterBundleEventCallback(sptr<BundleEventCallbackImpl> bundleEventCallback)
4087 {
4088     APP_LOGI("begin to call UnregisterBundleEventCallback");
4089     std::string msg;
4090     bool ret = bundleMgrProxy_->UnregisterBundleEventCallback(bundleEventCallback);
4091     if (!ret) {
4092         msg = "UnregisterBundleEventCallback failed";
4093         resultReceiver_.append(msg).append(LINE_BREAK);
4094         APP_LOGE("%{public}s", msg.c_str());
4095         return OHOS::ERR_INVALID_VALUE;
4096     }
4097     msg = "UnregisterBundleEventCallback success";
4098     resultReceiver_.append(msg).append(LINE_BREAK);
4099     APP_LOGI("%{public}s", msg.c_str());
4100     return OHOS::ERR_OK;
4101 }
4102 
HandleBundleEventCallback()4103 ErrCode BundleTestTool::HandleBundleEventCallback()
4104 {
4105     APP_LOGI("begin to HandleBundleEventCallback");
4106     bool onlyUnregister = false;
4107     int32_t uid = Constants::FOUNDATION_UID;
4108     if (!ParseEventCallbackOptions(onlyUnregister, uid)) {
4109         APP_LOGE("ParseEventCallbackOptions failed");
4110         return OHOS::ERR_INVALID_VALUE;
4111     }
4112     APP_LOGI("onlyUnregister : %{public}d, uid : %{public}d", onlyUnregister, uid);
4113     if (bundleMgrProxy_ == nullptr) {
4114         std::string msg = "bundleMgrProxy_ is nullptr";
4115         resultReceiver_.append(msg).append(LINE_BREAK);
4116         APP_LOGE("%{public}s", msg.c_str());
4117         return OHOS::ERR_INVALID_VALUE;
4118     }
4119     seteuid(uid);
4120     ErrCode ret;
4121     sptr<BundleEventCallbackImpl> bundleEventCallback = new (std::nothrow) BundleEventCallbackImpl();
4122     if (onlyUnregister) {
4123         // only call UnRegisterBundleEventCallback
4124         return CallUnRegisterBundleEventCallback(bundleEventCallback);
4125     }
4126     // call RegisterBundleEventCallback then call UnRegisterBundleEventCallback
4127     ret = CallRegisterBundleEventCallback(bundleEventCallback);
4128     if (ret != OHOS::ERR_OK) {
4129         return ret;
4130     }
4131     Sleep(SLEEP_SECONDS);
4132     ret = CallUnRegisterBundleEventCallback(bundleEventCallback);
4133     if (ret != OHOS::ERR_OK) {
4134         return ret;
4135     }
4136     Sleep(SLEEP_SECONDS);
4137     return OHOS::ERR_OK;
4138 }
4139 
ResetAOTCompileStatus()4140 ErrCode BundleTestTool::ResetAOTCompileStatus()
4141 {
4142     APP_LOGI("begin to ResetAOTCompileStatus");
4143     std::string bundleName;
4144     std::string moduleName;
4145     int32_t triggerMode = 0;
4146     int32_t uid = -1;
4147     if (!ParseResetAOTCompileStatusOptions(bundleName, moduleName, triggerMode, uid)) {
4148         APP_LOGE("ParseResetAOTCompileStatusOptions failed");
4149         return OHOS::ERR_INVALID_VALUE;
4150     }
4151     APP_LOGI("bundleName : %{public}s, moduleName : %{public}s, triggerMode : %{public}d",
4152         bundleName.c_str(), moduleName.c_str(), triggerMode);
4153     if (bundleMgrProxy_ == nullptr) {
4154         std::string msg = "bundleMgrProxy_ is nullptr";
4155         resultReceiver_.append(msg).append(LINE_BREAK);
4156         APP_LOGE("%{public}s", msg.c_str());
4157         return OHOS::ERR_INVALID_VALUE;
4158     }
4159     if (uid == -1) {
4160         int32_t userId = 100;
4161         uid = bundleMgrProxy_->GetUidByBundleName(bundleName, userId);
4162     }
4163     APP_LOGI("uid : %{public}d", uid);
4164     seteuid(uid);
4165     ErrCode ret = bundleMgrProxy_->ResetAOTCompileStatus(bundleName, moduleName, triggerMode);
4166     APP_LOGI("ret : %{public}d", ret);
4167     return OHOS::ERR_OK;
4168 }
4169 
SendCommonEvent()4170 ErrCode BundleTestTool::SendCommonEvent()
4171 {
4172     APP_LOGI("begin to SendCommonEvent");
4173     OHOS::AAFwk::Want want;
4174     want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED);
4175     EventFwk::CommonEventData commonData { want };
4176     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
4177     return OHOS::ERR_OK;
4178 }
4179 
RunAsQueryDataGroupInfos()4180 ErrCode BundleTestTool::RunAsQueryDataGroupInfos()
4181 {
4182     APP_LOGI("RunAsQueryDataGroupInfos start");
4183     std::string bundleName;
4184     int32_t userId;
4185     int32_t appIndex;
4186     int32_t result = BundleNameAndUserIdCommonFunc(bundleName, userId, appIndex);
4187     if (result != OHOS::ERR_OK) {
4188         resultReceiver_.append(HELP_MSG_QUERY_DATA_GROUP_INFOS);
4189     } else {
4190         std::string msg;
4191         result = QueryDataGroupInfos(bundleName, userId, msg);
4192         if (result) {
4193             resultReceiver_ = STRING_QUERY_DATA_GROUP_INFOS_OK + msg;
4194             return ERR_OK;
4195         } else {
4196             resultReceiver_ = STRING_QUERY_DATA_GROUP_INFOS_NG + "\n";
4197         }
4198     }
4199     return OHOS::ERR_INVALID_VALUE;
4200 }
4201 
QueryDataGroupInfos(const std::string & bundleName,int32_t userId,std::string & msg)4202 bool BundleTestTool::QueryDataGroupInfos(const std::string &bundleName,
4203     int32_t userId, std::string& msg)
4204 {
4205     if (bundleMgrProxy_ == nullptr) {
4206         APP_LOGE("bundleMgrProxy_ is nullptr");
4207         return OHOS::ERR_INVALID_VALUE;
4208     }
4209     std::vector<DataGroupInfo> infos;
4210     bool ret = bundleMgrProxy_->QueryDataGroupInfos(bundleName, userId, infos);
4211     if (ret) {
4212         msg = "dataGroupInfos:\n{\n";
4213         for (const auto &dataGroupInfo : infos) {
4214             msg +="     ";
4215             msg += dataGroupInfo.ToString();
4216             msg += "\n";
4217         }
4218         msg += "}\n";
4219         return true;
4220     }
4221 
4222     return false;
4223 }
4224 
RunAsGetGroupDir()4225 ErrCode BundleTestTool::RunAsGetGroupDir()
4226 {
4227     APP_LOGI("RunAsGetGroupDir start");
4228     ErrCode result;
4229     std::string dataGroupId;
4230     int32_t counter = 0;
4231     while (true) {
4232         counter++;
4233         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_GROUP_DIR.c_str(),
4234             LONG_OPTIONS_GET_GROUP_DIR, nullptr);
4235         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4236         if (optind < 0 || optind > argc_) {
4237             return OHOS::ERR_INVALID_VALUE;
4238         }
4239         if (option == -1) {
4240             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4241                 resultReceiver_.append(HELP_MSG_GET_GROUP_DIR);
4242                 return OHOS::ERR_INVALID_VALUE;
4243             }
4244             break;
4245         }
4246         result = CheckGetGroupIdCorrectOption(option, dataGroupId);
4247         if (result != OHOS::ERR_OK) {
4248             resultReceiver_.append(HELP_MSG_GET_GROUP_DIR);
4249             return OHOS::ERR_INVALID_VALUE;
4250         }
4251     }
4252     std::string msg;
4253     bool ret = GetGroupDir(dataGroupId, msg);
4254     if (ret) {
4255         resultReceiver_ = STRING_GET_GROUP_DIR_OK + msg;
4256     } else {
4257         resultReceiver_ = STRING_GET_GROUP_DIR_NG + "\n";
4258         APP_LOGE("RunAsGetGroupDir fail");
4259         return OHOS::ERR_INVALID_VALUE;
4260     }
4261     return result;
4262 }
4263 
CheckGetGroupIdCorrectOption(int32_t option,std::string & dataGroupId)4264 ErrCode BundleTestTool::CheckGetGroupIdCorrectOption(int32_t option, std::string &dataGroupId)
4265 {
4266     ErrCode result = OHOS::ERR_OK;
4267     switch (option) {
4268         case 'h': {
4269             result = OHOS::ERR_INVALID_VALUE;
4270             break;
4271         }
4272         case 'd': {
4273             dataGroupId = optarg;
4274             if (dataGroupId.size() == 0) {
4275                 return OHOS::ERR_INVALID_VALUE;
4276             }
4277             break;
4278         }
4279         default: {
4280             result = OHOS::ERR_INVALID_VALUE;
4281             break;
4282         }
4283     }
4284     return result;
4285 }
4286 
GetGroupDir(const std::string & dataGroupId,std::string & msg)4287 bool BundleTestTool::GetGroupDir(const std::string &dataGroupId, std::string& msg)
4288 {
4289     if (bundleMgrProxy_ == nullptr) {
4290         APP_LOGE("bundleMgrProxy_ is nullptr");
4291         return OHOS::ERR_INVALID_VALUE;
4292     }
4293     std::string dir;
4294     bool ret = bundleMgrProxy_->GetGroupDir(dataGroupId, dir);
4295     if (ret) {
4296         msg = "group dir:\n";
4297         msg += dir;
4298         msg += "\n";
4299         return true;
4300     }
4301 
4302     return false;
4303 }
4304 
CheckGetBundleNameOption(int32_t option,std::string & bundleName)4305 ErrCode BundleTestTool::CheckGetBundleNameOption(int32_t option, std::string &bundleName)
4306 {
4307     ErrCode result = OHOS::ERR_OK;
4308     switch (option) {
4309         case 'h': {
4310             result = OHOS::ERR_INVALID_VALUE;
4311             break;
4312         }
4313         case 'n': {
4314             bundleName = optarg;
4315             if (bundleName.size() == 0) {
4316                 return OHOS::ERR_INVALID_VALUE;
4317             }
4318             break;
4319         }
4320         default: {
4321             result = OHOS::ERR_INVALID_VALUE;
4322             break;
4323         }
4324     }
4325     return result;
4326 }
4327 
RunAsGetJsonProfile()4328 ErrCode BundleTestTool::RunAsGetJsonProfile()
4329 {
4330     APP_LOGI("RunAsGetJsonProfile start");
4331     int result = OHOS::ERR_OK;
4332     int counter = 0;
4333     std::string commandName = "getJsonProfile";
4334     std::string name = "";
4335     std::string bundleName = "";
4336     std::string moduleName = "";
4337     int jsonProfileType = -1;
4338     int userId = 100;
4339     APP_LOGD("RunAsGetStringCommand is start");
4340     while (true) {
4341         counter++;
4342         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_JSON_PROFILE.c_str(),
4343             LONG_OPTIONS_GET_JSON_PROFILE, nullptr);
4344         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4345         if (optind < 0 || optind > argc_) {
4346             return OHOS::ERR_INVALID_VALUE;
4347         }
4348         if (option == -1) {
4349             // When scanning the first argument
4350             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4351                 // 'GetStringById' with no option: GetStringById
4352                 // 'GetStringById' with a wrong argument: GetStringById
4353                 APP_LOGD("bundle_test_tool getStr with no option.");
4354                 resultReceiver_.append(HELP_MSG_NO_GET_JSON_PROFILE_OPTION);
4355                 return OHOS::ERR_INVALID_VALUE;
4356             }
4357             break;
4358         }
4359         int temp = 0;
4360         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4361             ? OHOS::ERR_INVALID_VALUE : result;
4362         moduleName = option == 'm' ? name : moduleName;
4363         bundleName = option == 'n' ? name : bundleName;
4364         userId = option == 'u' ? temp : userId;
4365         jsonProfileType = option == 'p' ? temp : jsonProfileType;
4366     }
4367 
4368     if (result != OHOS::ERR_OK) {
4369         resultReceiver_.append(HELP_MSG_GET_STRING);
4370     } else {
4371         std::string results = "";
4372         auto res = bundleMgrProxy_->GetJsonProfile(static_cast<ProfileType>(jsonProfileType),
4373             bundleName, moduleName, results, userId);
4374         if (res != OHOS::ERR_OK || results.empty()) {
4375             resultReceiver_.append(STRING_GET_JSON_PROFILE_NG);
4376             return result;
4377         }
4378         resultReceiver_.append(results);
4379         resultReceiver_.append("\n");
4380     }
4381     return result;
4382 }
4383 
RunGetUidByBundleName()4384 ErrCode BundleTestTool::RunGetUidByBundleName()
4385 {
4386     APP_LOGI("RunGetUidByBundleName start");
4387     int result = OHOS::ERR_OK;
4388     int counter = 0;
4389     std::string name = "";
4390     std::string commandName = "getUidByBundleName";
4391     std::string bundleName = "";
4392     int userId = 100;
4393     int appIndex = 0;
4394     APP_LOGD("RunGetIntCommand is start");
4395     bool flag = true;
4396     while (flag) {
4397         counter++;
4398         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_UID_BY_BUNDLENAME.c_str(),
4399             LONG_OPTIONS_GET_UID_BY_BUNDLENAME, nullptr);
4400         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4401         if (optind < 0 || optind > argc_) {
4402             return OHOS::ERR_INVALID_VALUE;
4403         }
4404         if (option == -1) {
4405             // When scanning the first argument
4406             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4407                 APP_LOGD("bundle_test_tool getUidByBundleName with no option.");
4408                 resultReceiver_.append(HELP_MSG_NO_GET_UID_BY_BUNDLENAME);
4409                 return OHOS::ERR_INVALID_VALUE;
4410             }
4411             break;
4412         }
4413         int temp = 0;
4414         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4415             ? OHOS::ERR_INVALID_VALUE : result;
4416         bundleName = option == 'n' ? name : bundleName;
4417         userId = option == 'u' ? temp : userId;
4418         appIndex = option == 'a' ? temp : appIndex;
4419     }
4420 
4421     if (result != OHOS::ERR_OK) {
4422         resultReceiver_.append(HELP_MSG_NO_GET_UID_BY_BUNDLENAME);
4423     } else {
4424         int32_t res = bundleMgrProxy_->GetUidByBundleName(bundleName, userId, appIndex);
4425         if (res == -1) {
4426             resultReceiver_.append(STRING_GET_UID_BY_BUNDLENAME_NG);
4427             return result;
4428         }
4429         resultReceiver_.append(std::to_string(res));
4430         resultReceiver_.append("\n");
4431     }
4432     return result;
4433 }
4434 
RunAsGetUninstalledBundleInfo()4435 ErrCode BundleTestTool::RunAsGetUninstalledBundleInfo()
4436 {
4437     APP_LOGI("RunAsGetUninstalledBundleInfo start");
4438     int result = OHOS::ERR_OK;
4439     int counter = 0;
4440     std::string bundleName = "";
4441     while (true) {
4442         counter++;
4443         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_UNINSTALLED_BUNDLE_INFO.c_str(),
4444             LONG_OPTIONS_UNINSTALLED_BUNDLE_INFO, nullptr);
4445         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4446         if (optind < 0 || optind > argc_) {
4447             return OHOS::ERR_INVALID_VALUE;
4448         }
4449         if (option == -1) {
4450             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4451                 resultReceiver_.append(HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION);
4452                 return OHOS::ERR_INVALID_VALUE;
4453             }
4454             break;
4455         }
4456         result = CheckGetBundleNameOption(option, bundleName);
4457         APP_LOGD("getUninstalledBundleInfo optind: %{public}s", bundleName.c_str());
4458     }
4459 
4460     if (result != OHOS::ERR_OK) {
4461         resultReceiver_.append(HELP_MSG_NO_GET_UNINSTALLED_BUNDLE_INFO_OPTION);
4462     } else {
4463         BundleInfo bundleInfo;
4464         auto res = bundleMgrProxy_->GetUninstalledBundleInfo(bundleName, bundleInfo);
4465         if (res != OHOS::ERR_OK) {
4466             resultReceiver_.append(STRING_GET_UNINSTALLED_BUNDLE_INFO_NG);
4467             return result;
4468         }
4469         nlohmann::json jsonObject = bundleInfo;
4470         jsonObject["applicationInfo"] = bundleInfo.applicationInfo;
4471         std::string results = jsonObject.dump(Constants::DUMP_INDENT);
4472         resultReceiver_.append(results);
4473         resultReceiver_.append("\n");
4474     }
4475     return result;
4476 }
4477 
RunAsGetOdid()4478 ErrCode BundleTestTool::RunAsGetOdid()
4479 {
4480     std::string commandName = "getOdid";
4481     int uid = Constants::INVALID_UID;
4482     int opt = 0;
4483 
4484     const std::map<char, OptionHandler> getOdidOptionHandlers = {
4485         {'u', [&uid, &commandName, this](const std::string& value) {
4486             bool ret;
4487             StringToInt(value, commandName, uid, ret); }}
4488     };
4489     while ((opt = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_ODID.c_str(), LONG_OPTIONS_GET_ODID, nullptr)) != -1) {
4490         auto it = getOdidOptionHandlers.find(opt);
4491         if (it != getOdidOptionHandlers.end()) {
4492             it->second(optarg);
4493         } else {
4494             resultReceiver_.append(HELP_MSG_GET_ODID);
4495             return OHOS::ERR_INVALID_VALUE;
4496         }
4497     }
4498     std::string odid;
4499     setuid(uid);
4500     auto result = bundleMgrProxy_->GetOdid(odid);
4501     setuid(Constants::ROOT_UID);
4502     if (result == ERR_OK) {
4503         resultReceiver_.append(STRING_GET_ODID_OK);
4504         resultReceiver_.append(odid + "\n");
4505     } else if (result == ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST) {
4506         resultReceiver_.append(STRING_GET_ODID_NG + "Please enter a valid uid\n");
4507     } else {
4508         resultReceiver_.append(STRING_GET_ODID_NG + "errCode is "+ std::to_string(result) + "\n");
4509     }
4510     return result;
4511 }
4512 
CheckImplicitQueryWantOption(int option,std::string & value)4513 ErrCode BundleTestTool::CheckImplicitQueryWantOption(int option, std::string &value)
4514 {
4515     ErrCode result = OHOS::ERR_OK;
4516     switch (option) {
4517         case 'n': {
4518             value = optarg;
4519             break;
4520         }
4521         case 'a': {
4522             value = optarg;
4523             break;
4524         }
4525         case 'e': {
4526             value = optarg;
4527             break;
4528         }
4529         case 'u': {
4530             value = optarg;
4531             break;
4532         }
4533         case 't': {
4534             value = optarg;
4535             break;
4536         }
4537         default: {
4538             std::string unknownOption = "";
4539             std::string unknownOptionMsg = GetUnknownOptionMsg(unknownOption);
4540             resultReceiver_.append(unknownOptionMsg);
4541             result = OHOS::ERR_INVALID_VALUE;
4542             break;
4543         }
4544     }
4545     return result;
4546 }
4547 
ImplicitQuerySkillUriInfo(const std::string & bundleName,const std::string & action,const std::string & entity,const std::string & uri,const std::string & type,std::string & msg)4548 ErrCode BundleTestTool::ImplicitQuerySkillUriInfo(const std::string &bundleName,
4549     const std::string &action, const std::string &entity, const std::string &uri,
4550     const std::string &type, std::string &msg)
4551 {
4552     if (bundleMgrProxy_ == nullptr) {
4553         APP_LOGE("bundleMgrProxy_ is nullptr");
4554         return OHOS::ERR_INVALID_VALUE;
4555     }
4556     AAFwk::Want want;
4557     want.SetAction(action);
4558     want.AddEntity(entity);
4559     ElementName elementName("", bundleName, "", "");
4560     want.SetElement(elementName);
4561     want.SetUri(uri);
4562     want.SetType(type);
4563 
4564     int32_t userId = BundleCommandCommon::GetCurrentUserId(Constants::UNSPECIFIED_USERID);
4565     std::vector<AbilityInfo> abilityInfos;
4566     int32_t flags = static_cast<int32_t>(GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_SKILL_URI);
4567     ErrCode res = bundleMgrProxy_->QueryAbilityInfosV9(want, flags, userId, abilityInfos);
4568     if (res != OHOS::ERR_OK) {
4569         return res;
4570     }
4571     for (auto &ability: abilityInfos) {
4572         msg += "Ability start\n";
4573         for (auto &uri: ability.skillUri) {
4574             msg += "{\n";
4575             msg += "    scheme: " + uri.scheme + "\n";
4576             msg += "    host: " + uri.host + "\n";
4577             msg += "    port: " + uri.port + "\n";
4578             msg += "    path: " + uri.path + "\n";
4579             msg += "    pathStartWith: " + uri.pathStartWith + "\n";
4580             msg += "    pathRegex: " + uri.pathRegex + "\n";
4581             msg += "    type: " + uri.type + "\n";
4582             msg += "    utd: " + uri.utd + "\n";
4583             msg += "    maxFileSupported: " + std::to_string(uri.maxFileSupported) + "\n";
4584             msg += "    linkFeature: " + uri.linkFeature + "\n";
4585             msg += "    isMatch: " + std::to_string(uri.isMatch) + "\n";
4586             msg += "}\n";
4587         }
4588         msg += "Ability end\n";
4589     }
4590     return res;
4591 }
4592 
RunAsImplicitQuerySkillUriInfo()4593 ErrCode BundleTestTool::RunAsImplicitQuerySkillUriInfo()
4594 {
4595     APP_LOGI("RunAsGetAbilityInfoWithSkillUriFlag start");
4596     int result = OHOS::ERR_OK;
4597     int counter = 0;
4598     std::string bundleName = "";
4599     std::string action = "";
4600     std::string entity = "";
4601     std::string uri = "";
4602     std::string type = "";
4603     while (true) {
4604         counter++;
4605         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO.c_str(),
4606             LONG_OPTIONS_IMPLICIT_QUERY_SKILL_URI_INFO, nullptr);
4607         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4608         if (optind < 0 || optind > argc_) {
4609             return OHOS::ERR_INVALID_VALUE;
4610         }
4611         if (option == -1) {
4612             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4613                 resultReceiver_.append(HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO);
4614                 return OHOS::ERR_INVALID_VALUE;
4615             }
4616             break;
4617         }
4618         std::string value = "";
4619         result = CheckImplicitQueryWantOption(option, value);
4620         bundleName = option == 'n' ? value : bundleName;
4621         action = option == 'a' ? value : action;
4622         entity = option == 'e' ? value : entity;
4623         uri = option == 'u' ? value : uri;
4624         type = option == 't' ? value : type;
4625     }
4626     APP_LOGI("bundleName: %{public}s, action: %{public}s, entity: %{public}s, uri: %{public}s, type: %{public}s",
4627         bundleName.c_str(), action.c_str(), entity.c_str(), uri.c_str(), type.c_str());
4628     if (result != OHOS::ERR_OK) {
4629         resultReceiver_.append(HELP_MSG_NO_IMPLICIT_QUERY_SKILL_URI_INFO);
4630     } else {
4631         std::string msg;
4632         result = ImplicitQuerySkillUriInfo(bundleName, action, entity, uri, type, msg);
4633         if (result != OHOS::ERR_OK) {
4634             resultReceiver_.append(STRING_IMPLICIT_QUERY_SKILL_URI_INFO_NG);
4635         } else {
4636             resultReceiver_.append(msg);
4637         }
4638         resultReceiver_.append("\n");
4639     }
4640     return result;
4641 }
4642 
RunAsQueryAbilityInfoByContinueType()4643 ErrCode BundleTestTool::RunAsQueryAbilityInfoByContinueType()
4644 {
4645     APP_LOGI("RunAsQueryAbilityInfoByContinueType start");
4646     int result = OHOS::ERR_OK;
4647     int counter = 0;
4648     std::string commandName = "queryAbilityInfoByContinueType";
4649     std::string name = "";
4650     std::string bundleName = "";
4651     std::string continueType = "";
4652     int userId = 100;
4653     while (true) {
4654         counter++;
4655         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE.c_str(),
4656             LONG_OPTIONS_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE, nullptr);
4657         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4658         if (optind < 0 || optind > argc_) {
4659             return OHOS::ERR_INVALID_VALUE;
4660         }
4661         if (option == -1) {
4662             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4663                 resultReceiver_.append(HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE);
4664                 return OHOS::ERR_INVALID_VALUE;
4665             }
4666             break;
4667         }
4668         int temp = 0;
4669         result = !CheckGetStringCorrectOption(option, commandName, temp, name)
4670             ? OHOS::ERR_INVALID_VALUE : result;
4671         bundleName = option == 'n' ? name : bundleName;
4672         continueType = option == 'c' ? name : continueType;
4673         userId = option == 'u' ? temp : userId;
4674     }
4675     APP_LOGI("bundleName: %{public}s, continueType: %{public}s, userId: %{public}d",
4676         bundleName.c_str(), continueType.c_str(), userId);
4677     if (result != OHOS::ERR_OK) {
4678         resultReceiver_.append(HELP_MSG_NO_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE);
4679     } else {
4680         AbilityInfo abilityInfo;
4681         result = bundleMgrProxy_->QueryAbilityInfoByContinueType(bundleName, continueType, abilityInfo, userId);
4682         if (result != OHOS::ERR_OK) {
4683             resultReceiver_.append(STRING_QUERY_ABILITY_INFO_BY_CONTINUE_TYPE_NG);
4684         } else {
4685             nlohmann::json jsonObject = abilityInfo;
4686             std::string results = jsonObject.dump(Constants::DUMP_INDENT);
4687             resultReceiver_.append(results);
4688         }
4689         resultReceiver_.append("\n");
4690     }
4691     return result;
4692 }
4693 
InnerGetSimpleAppInfoForUid(const int32_t & option,std::vector<std::int32_t> & uids)4694 ErrCode BundleTestTool::InnerGetSimpleAppInfoForUid(const int32_t &option, std::vector<std::int32_t> &uids)
4695 {
4696     std::string commandName = "getSimpleAppInfoForUid";
4697     int32_t uid = Constants::FOUNDATION_UID;
4698     switch (option) {
4699         case 'u': {
4700             std::string arrayUId = optarg;
4701             std::stringstream array(arrayUId);
4702             std::string object;
4703             bool ret = true;
4704             while (getline(array, object, ',')) {
4705                 StringToInt(object, commandName, uid, ret);
4706                 if (!ret) {
4707                     resultReceiver_.append(HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID);
4708                     return OHOS::ERR_INVALID_VALUE;
4709                 }
4710                 uids.emplace_back(uid);
4711             }
4712             APP_LOGD("bundle_test_tool %{public}s -u %{public}s", commandName.c_str(), argv_[optind - 1]);
4713             break;
4714         }
4715         default: {
4716             resultReceiver_.append(HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID);
4717             return OHOS::ERR_INVALID_VALUE;
4718         }
4719     }
4720     return OHOS::ERR_OK;
4721 }
4722 
RunAsGetSimpleAppInfoForUid()4723 ErrCode BundleTestTool::RunAsGetSimpleAppInfoForUid()
4724 {
4725     APP_LOGI("RunAsGetSimpleAppInfoForUid start");
4726     std::vector<std::int32_t> uids;
4727     int32_t counter = 0;
4728     while (counter <= 1) {
4729         counter++;
4730         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID.c_str(),
4731             LONG_OPTIONS_GET_SIMPLE_APP_INFO_FOR_UID, nullptr);
4732         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4733         if (optind < 0 || optind > argc_) {
4734             return OHOS::ERR_INVALID_VALUE;
4735         }
4736         if (option == -1) {
4737             // When scanning the first argument
4738             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4739                 APP_LOGD("bundle_test_tool getSimpleAppInfoForUid with no option.");
4740                 resultReceiver_.append(HELP_MSG_GET_SIMPLE_APP_INFO_FOR_UID);
4741                 return OHOS::ERR_INVALID_VALUE;
4742             }
4743             break;
4744         }
4745         auto ret = InnerGetSimpleAppInfoForUid(option, uids);
4746         if (ret != OHOS::ERR_OK) {
4747             return ret;
4748         }
4749     }
4750     std::vector<SimpleAppInfo> simpleAppInfo;
4751     auto result = bundleMgrProxy_->GetSimpleAppInfoForUid(uids, simpleAppInfo);
4752     if (result == ERR_OK) {
4753         resultReceiver_.append(STRING_GET_SIMPLE_APP_INFO_FOR_UID_OK);
4754         for (size_t i = 0; i < simpleAppInfo.size(); i++) {
4755             resultReceiver_.append(simpleAppInfo[i].ToString() + "\n");
4756         }
4757     } else {
4758         resultReceiver_.append(STRING_GET_SIMPLE_APP_INFO_FOR_UID_NG + "errCode is "+ std::to_string(result) + "\n");
4759     }
4760     APP_LOGI("RunAsGetSimpleAppInfoForUid end");
4761     return result;
4762 }
4763 
RunAsGetBundleNameByAppId()4764 ErrCode BundleTestTool::RunAsGetBundleNameByAppId()
4765 {
4766     APP_LOGI("RunAsGetBundleNameByAppId start");
4767     std::string appId;
4768     std::string bundleName;
4769     int32_t counter = 0;
4770     while (true) {
4771         counter++;
4772         int32_t option = getopt_long(argc_, argv_, SHORT_OPTIONS_GET_BUNDLENAME_BY_APPID.c_str(),
4773             LONG_OPTIONS_GET_BUNDLENAME_BY_APPID, nullptr);
4774         APP_LOGD("option: %{public}d, optopt: %{public}d, optind: %{public}d", option, optopt, optind);
4775         if (optind < 0 || optind > argc_) {
4776             return OHOS::ERR_INVALID_VALUE;
4777         }
4778         if (option == -1) {
4779             // When scanning the first argument
4780             if ((counter == 1) && (strcmp(argv_[optind], cmd_.c_str()) == 0)) {
4781                 APP_LOGD("bundle_test_tool isBundleInstalled with no option.");
4782                 resultReceiver_.append(HELP_MSG_GET_BUNDLENAME_BY_APPID);
4783                 return OHOS::ERR_INVALID_VALUE;
4784             }
4785             break;
4786         }
4787         switch (option) {
4788             case 'a': {
4789                 appId = optarg;
4790                 break;
4791             }
4792             default: {
4793                 resultReceiver_.append(HELP_MSG_GET_BUNDLENAME_BY_APPID);
4794                 return OHOS::ERR_INVALID_VALUE;
4795             }
4796         }
4797     }
4798     auto result = bundleMgrProxy_->GetBundleNameByAppId(appId, bundleName);
4799     if (result == ERR_OK) {
4800         resultReceiver_.append(STRING_GET_BUNDLENAME_BY_APPID_OK);
4801         resultReceiver_.append(bundleName + "\n");
4802     } else {
4803         resultReceiver_.append(STRING_GET_BUNDLENAME_BY_APPID_NG + "errCode is "+ std::to_string(result) + "\n");
4804     }
4805     APP_LOGI("RunAsGetBundleNameByAppId end");
4806     return result;
4807 }
4808 } // AppExecFwk
4809 } // OHOS