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