1 /*
2  * Copyright (c) 2021 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 <cstdlib>
16 #include <getopt.h>
17 #include <iostream>
18 #include <iomanip>
19 #include <ctime>
20 #include <functional>
21 #include <string_ex.h>
22 #include <securec.h>
23 #include <list>
24 
25 #include <hilog/log.h>
26 #include <hilog_common.h>
27 #include <log_utils.h>
28 #include <log_ioctl.h>
29 #include <log_print.h>
30 #include <properties.h>
31 
32 #include "log_display.h"
33 
34 namespace OHOS {
35 namespace HiviewDFX {
36 using namespace std;
FormatHelper()37 static void FormatHelper()
38 {
39     cout
40     << "  -v <format>, --format=<format>" << endl
41     << "    Show logs in different formats, options are:" << endl
42     << "      color or colour      display colorful logs by log level.i.e." << endl
43     << "        \x1B[38;5;75mDEBUG        \x1B[38;5;40mINFO        \x1B[38;5;166mWARN"
44     << "        \x1B[38;5;196mERROR       \x1B[38;5;226mFATAL\x1B[0m" << endl
45     << "      time format options are(single accepted):" << endl
46     << "        time       display local time, this is default." << endl
47     << "        epoch      display the time from 1970/1/1." << endl
48     << "        monotonic  display the cpu time from bootup." << endl
49     << "      time accuracy format options are(single accepted):" << endl
50     << "        msec       display time by millisecond, this is default." << endl
51     << "        usec       display time by microsecond." << endl
52     << "        nsec       display time by nanosecond." << endl
53     << "      year       display the year when -v time is specified." << endl
54     << "      zone       display the time zone when -v time is specified." << endl
55     << "      wrap       display the log without prefix when a log line is wrapped." << endl
56     << "    Different types of formats can be combined, such as:" << endl
57     << "    -v color -v time -v msec -v year -v zone." << endl;
58 }
59 
QueryHelper()60 static void QueryHelper()
61 {
62     cout
63     << "Querying logs options:" << endl
64     << "  No option performs a blocking read and keeps printing." << endl
65     << "  -x --exit" << endl
66     << "    Performs a non-blocking read and exits when all logs in buffer are printed." << endl
67     << "  -a <n>, --head=<n>" << endl
68     << "    Show n lines logs on head of buffer." << endl
69     << "  -z <n>, --tail=<n>" << endl
70     << "    Show n lines logs on tail of buffer." << endl
71     << "  -t <type>, --type=<type>" << endl
72     << "    Show specific type/types logs with format: type1,type2,type3" << endl
73     << "    Don't show specific type/types logs with format: ^type1,type2,type3" << endl
74     << "    Type coule be: app/core/init/kmsg/only_prerelease, kmsg can't combine with others." << endl
75     << "    Default types are: app,core,init,only_prerelease." << endl
76     << "  -L <level>, --level=<level>" << endl
77     << "    Show specific level/levels logs with format: level1,level2,level3" << endl
78     << "    Don't show specific level/levels logs with format: ^level1,level2,level3" << endl
79     << "    Long and short level string are both accepted" << endl
80     << "    Long level string coule be: DEBUG/INFO/WARN/ERROR/FATAL." << endl
81     << "    Short level string coule be: D/I/W/E/F." << endl
82     << "    Default levels are all levels." << endl
83     << "  -D <domain>, --domain=<domain>" << endl
84     << "    Show specific domain/domains logs with format: domain1,domain2,doman3" << endl
85     << "    Don't show specific domain/domains logs with format: ^domain1,domain2,doman3" << endl
86     << "    Max domain count is " << MAX_DOMAINS << "." << endl
87     << "    See domain description at the end of this message." << endl
88     << "  -T <tag>, --tag=<tag>" << endl
89     << "    Show specific tag/tags logs with format: tag1,tag2,tag3" << endl
90     << "    Don't show specific tag/tags logs with format: ^tag1,tag2,tag3" << endl
91     << "    Max tag count is " << MAX_TAGS << "." << endl
92     << "  -P <pid>, --pid=<pid>" << endl
93     << "    Show specific pid/pids logs with format: pid1,pid2,pid3" << endl
94     << "    Don't show specific domain/domains logs with format: ^pid1,pid2,pid3" << endl
95     << "    Max pid count is " << MAX_PIDS << "." << endl
96     << "  -e <expr>, --regex=<expr>" << endl
97     << "    Show the logs which match the regular expression <expr>." << endl;
98     FormatHelper();
99 }
100 
ClearHelper()101 static void ClearHelper()
102 {
103     cout
104     << "-r" << endl
105     << "  Remove all logs in hilogd buffer, advanced option:" << endl
106     << "  -t <type>, --type=<type>" << endl
107     << "    Remove specific type/types logs in buffer with format: type1,type2,type3" << endl
108     << "    Type coule be: app/core/init/kmsg/only_prerelease." << endl
109     << "    Default types are: app,core,only_prerelease" << endl;
110 }
111 
BufferHelper()112 static void BufferHelper()
113 {
114     cout
115     << "-g" << endl
116     << "  Query hilogd buffer size, advanced option:" << endl
117     << "  -t <type>, --type=<type>" << endl
118     << "    Query specific type/types buffer size with format: type1,type2,type3" << endl
119     << "    Type coule be: app/core/init/kmsg/only_prerelease." << endl
120     << "    Default types are: app,core,only_prerelease" << endl
121     << "-G <size>, --buffer-size=<size>" << endl
122     << "  Set hilogd buffer size, <size> could be number or number with unit." << endl
123     << "  Unit could be: B/K/M/G which represents Byte/Kilobyte/Megabyte/Gigabyte." << endl
124     << "  <size> range: [" << Size2Str(MIN_BUFFER_SIZE) << "," << Size2Str(MIN_BUFFER_SIZE) << "]." << endl
125     << "  Advanced option:" << endl
126     << "  -t <type>, --type=<type>" << endl
127     << "    Set specific type/types log buffer size with format: type1,type2,type3" << endl
128     << "    Type coule be: app/core/init/kmsg/only_prerelease." << endl
129     << "    Default types are: app,core,only_prerelease" << endl
130     << "  **It's a persistant configuration**" << endl;
131 }
132 
StatisticHelper()133 static void StatisticHelper()
134 {
135     cout
136     << "-s, --statistics" << endl
137     << "  Query log statistic information." << endl
138     << "  Set param persist.sys.hilog.stats true to enable statistic." << endl
139     << "  Set param persist.sys.hilog.stats.tag true to enable statistic of log tag." << endl
140     << "-S" << endl
141     << "  Clear hilogd statistic information." << endl;
142 }
143 
PersistTaskHelper()144 static void PersistTaskHelper()
145 {
146     cout
147     << "-w <control>,--write=<control>" << endl
148     << "  Log persistance task control, options are:" << endl
149     << "    query      query tasks informations" << endl
150     << "    stop       stop all tasks" << endl
151     << "    start      start one task" << endl
152     << "    refresh    refresh buffer content to file" << endl
153     << "    clear      clear /data/log/hilog/hilog*.gz" << endl
154     << "  Persistance task is used for saving logs in files." << endl
155     << "  The files are saved in directory: " << HILOG_FILE_DIR << endl
156     << "  Advanced options:" << endl
157     << "  -f <filename>, --filename=<filename>" << endl
158     << "    Set log file name, name should be valid of Linux FS." << endl
159     << "  -l <length>, --length=<length>" << endl
160     << "    Set single log file size. <length> could be number or number with unit." << endl
161     << "    Unit could be: B/K/M/G which represents Byte/Kilobyte/Megabyte/Gigabyte." << endl
162     << "    <length> range: [" << Size2Str(MIN_LOG_FILE_SIZE) <<", " << Size2Str(MAX_LOG_FILE_SIZE) << "]." << endl
163     << "  -n <number>, --number<number>" << endl
164     << "    Set max log file numbers, log file rotate when files count over this number." << endl
165     << "    <number> range: [" << MIN_LOG_FILE_NUM << ", " << MAX_LOG_FILE_NUM << "]." << endl
166     << "  -m <compress algorithm>,--stream=<compress algorithm>" << endl
167     << "    Set log file compressed algorithm, options are:" << endl
168     << "      none       write file with non-compressed logs." << endl
169     << "      zlib       write file with zlib compressed logs." << endl
170     << "  -j <jobid>, --jobid<jobid>" << endl
171     << "    Start/stop specific task of <jobid>." << endl
172     << "    <jobid> range: [" << JOB_ID_MIN << ", 0x" << hex << JOB_ID_MAX << dec << ")." << endl
173     << "  User can start task with options (t/L/D/T/P/e/v) as if using them when \"Query logs\" too." << endl
174     << "  **It's a persistant configuration**" << endl;
175 }
176 
PrivateHelper()177 static void PrivateHelper()
178 {
179     cout
180     << "-p <on/off>, --privacy <on/off>" << endl
181     << "  Set HILOG api privacy formatter feature on or off." << endl
182     << "  **It's a temporary configuration, will be lost after reboot**" << endl;
183 }
184 
KmsgHelper()185 static void KmsgHelper()
186 {
187     cout
188     << "-k <on/off>, --kmsg <on/off>" << endl
189     << "  Set hilogd storing kmsg log feature on or off" << endl
190     << "  **It's a persistant configuration**" << endl;
191 }
192 
FlowControlHelper()193 static void FlowControlHelper()
194 {
195     cout
196     << "-Q <control-type>" << endl
197     << "  Set log flow-control feature on or off, options are:" << endl
198     << "    pidon     process flow control on" << endl
199     << "    pidoff    process flow control off" << endl
200     << "    domainon  domain flow control on" << endl
201     << "    domainoff domain flow control off" << endl
202     << "  **It's a temporary configuration, will be lost after reboot**" << endl;
203 }
204 
BaseLevelHelper()205 static void BaseLevelHelper()
206 {
207     cout
208     << "-b <loglevel>, --baselevel=<loglevel>" << endl
209     << "  Set global loggable level to <loglevel>" << endl
210     << "  Long and short level string are both accepted." << endl
211     << "  Long level string coule be: DEBUG/INFO/WARN/ERROR/FATAL/X." << endl
212     << "  Short level string coule be: D/I/W/E/F/X." << endl
213     << "  X means that loggable level is higher than the max level, no log could be printed." << endl
214     << "  Advanced options:" << endl
215     << "  -D <domain>, --domain=<domain>" << endl
216     << "    Set specific domain loggable level." << endl
217     << "    See domain description at the end of this message." << endl
218     << "  -T <tag>, --tag=<tag>" << endl
219     << "    Set specific tag loggable level." << endl
220     << "    The priority is: tag level > domain level > global level." << endl
221     << "  **It's a temporary configuration, will be lost after reboot**" << endl;
222 }
223 
DomainHelper()224 static void DomainHelper()
225 {
226     cout
227     << endl << endl
228     << "Domain description:" << endl
229     << "  Log type \"core\" & \"init\" & \"only_prerelease\" are used for OS subsystems, the range is"
230     << "  [0x" << hex << DOMAIN_OS_MIN << ",  0x" << DOMAIN_OS_MAX << "]" << endl
231     << "  Log type \"app\" is used for applications, the range is [0x" << DOMAIN_APP_MIN << ","
232     << "  0x" << DOMAIN_APP_MAX << "]" << dec << endl
233     << "  To reduce redundant info when printing logs, only last five hex numbers of domain are printed" << endl
234     << "  So if user wants to use -D option to filter OS logs, user should add 0xD0 as prefix to the printed domain:"
235     << endl
236     << "  Exapmle: hilog -D 0xD0xxxxx" << endl
237     << "  The xxxxx is the domain string printed in logs." << endl;
238 }
239 
ComboHelper()240 static void ComboHelper()
241 {
242     cout
243     << "The first layer options can't be used in combination, ILLEGAL expamples:" << endl
244     << "    hilog -S -s; hilog -w start -r; hilog -p on -k on -b D" << endl;
245 }
246 
247 using HelperFunc = std::function<void()>;
248 static const std::list<pair<string, HelperFunc>> g_HelperList = {
249     {"query", QueryHelper},
250     {"clear", ClearHelper},
251     {"buffer", BufferHelper},
252     {"stats", StatisticHelper},
253     {"persist", PersistTaskHelper},
254     {"private", PrivateHelper},
255     {"kmsg", KmsgHelper},
256     {"flowcontrol", FlowControlHelper},
257     {"baselevel", BaseLevelHelper},
258     {"combo", ComboHelper},
259     {"domain", DomainHelper},
260 };
261 
Helper(const string & arg)262 static void Helper(const string& arg)
263 {
264     cout << "Usage:" << endl
265     << "-h --help" << endl
266     << "  Show all help information." << endl
267     << "  Show single help information with option: " << endl
268     << "  query/clear/buffer/stats/persist/private/kmsg/flowcontrol/baselevel/domain/combo" << endl;
269     for (auto &it : g_HelperList) {
270         if (arg == "" || arg == it.first) {
271             it.second();
272         }
273     }
274     return;
275 }
276 
PrintErr(int error)277 static void PrintErr(int error)
278 {
279     cerr << ErrorCode2Str(error) << endl;
280 }
281 
PrintResult(int ret,const string & msg)282 static void PrintResult(int ret, const string& msg)
283 {
284     cout << msg << ((ret == RET_SUCCESS) ? " successfully" : " failed") << endl;
285 }
286 
287 enum class ControlCmd {
288     NOT_CMD = -1,
289     CMD_HELP = 0,
290     CMD_QUERY,
291     CMD_REMOVE,
292     CMD_BUFFER_SIZE_QUERY,
293     CMD_BUFFER_SIZE_SET,
294     CMD_STATS_INFO_QUERY,
295     CMD_STATS_INFO_CLEAR,
296     CMD_PERSIST_TASK,
297     CMD_PRIVATE_FEATURE_SET,
298     CMD_KMSG_FEATURE_SET,
299     CMD_FLOWCONTROL_FEATURE_SET,
300     CMD_LOGLEVEL_SET,
301 };
302 
303 struct HilogArgs {
304     uint16_t headLines;
305     uint16_t baseLevel;
306     bool blackDomain;
307     int domainCount;
308     uint32_t domains[MAX_DOMAINS];
309     string regex;
310     string fileName;
311     int32_t buffSize;
312     uint32_t jobId;
313     uint32_t fileSize;
314     uint16_t levels;
315     string stream;
316     uint16_t fileNum;
317     bool blackPid;
318     int pidCount;
319     uint32_t pids[MAX_PIDS];
320     uint16_t types;
321     bool blackTag;
322     int tagCount;
323     string tags[MAX_TAGS];
324     bool colorful;
325     FormatTime timeFormat;
326     FormatTimeAccu timeAccuFormat;
327     bool year;
328     bool zone;
329     bool wrap;
330     bool noBlock;
331     uint16_t tailLines;
332 
HilogArgsOHOS::HiviewDFX::HilogArgs333     HilogArgs() : headLines (0), baseLevel(0), blackDomain(false), domainCount(0), domains { 0 }, regex(""),
334         fileName(""), buffSize(0), jobId(0), fileSize(0), levels(0), stream(""), fileNum(0), blackPid(false),
335         pidCount(0), pids { 0 }, types(0), blackTag(false), tagCount(0), tags { "" }, colorful(false),
336         timeFormat(FormatTime::INVALID), timeAccuFormat(FormatTimeAccu::INVALID), year(false), zone(false),
337         wrap(false), noBlock(false), tailLines(0) {}
338 
ToOutputRqstOHOS::HiviewDFX::HilogArgs339     void ToOutputRqst(OutputRqst& rqst)
340     {
341         rqst.headLines = headLines;
342         rqst.types = types;
343         rqst.levels = levels;
344         rqst.blackDomain = blackDomain;
345         rqst.domainCount = static_cast<uint8_t>(domainCount);
346         int i;
347         for (i = 0; i < domainCount; i++) {
348             rqst.domains[i] = domains[i];
349         }
350         rqst.blackTag = blackTag;
351         rqst.tagCount = tagCount;
352         for (i = 0; i < tagCount; i++) {
353             (void)strncpy_s(rqst.tags[i], MAX_TAG_LEN, tags[i].c_str(), tags[i].length());
354         }
355         rqst.blackPid = blackPid;
356         rqst.pidCount = pidCount;
357         for (i = 0; i < pidCount; i++) {
358             rqst.pids[i] = pids[i];
359         }
360         (void)strncpy_s(rqst.regex, MAX_REGEX_STR_LEN, regex.c_str(), regex.length());
361         rqst.noBlock = noBlock;
362         rqst.tailLines = tailLines;
363     }
364 
ToPersistStartRqstOHOS::HiviewDFX::HilogArgs365     void ToPersistStartRqst(PersistStartRqst& rqst)
366     {
367         ToOutputRqst(rqst.outputFilter);
368         rqst.jobId = jobId;
369         rqst.fileNum = fileNum;
370         rqst.fileSize = fileSize;
371         (void)strncpy_s(rqst.fileName, MAX_FILE_NAME_LEN, fileName.c_str(), fileName.length());
372         (void)strncpy_s(rqst.stream, MAX_STREAM_NAME_LEN, stream.c_str(), stream.length());
373     }
374 
ToPersistStopRqstOHOS::HiviewDFX::HilogArgs375     void ToPersistStopRqst(PersistStopRqst& rqst)
376     {
377         rqst.jobId = jobId;
378     }
379 
ToBufferSizeSetRqstOHOS::HiviewDFX::HilogArgs380     void ToBufferSizeSetRqst(BufferSizeSetRqst& rqst)
381     {
382         rqst.types = types;
383         rqst.size = buffSize;
384     }
385 
ToBufferSizeGetRqstOHOS::HiviewDFX::HilogArgs386     void ToBufferSizeGetRqst(BufferSizeGetRqst& rqst)
387     {
388         rqst.types = types;
389     }
390 
ToStatsQueryRqstOHOS::HiviewDFX::HilogArgs391     void ToStatsQueryRqst(StatsQueryRqst& rqst)
392     {
393         rqst.types = types;
394         rqst.domainCount = static_cast<uint8_t>(domainCount);
395         int i;
396         for (i = 0; i < domainCount; i++) {
397             rqst.domains[i] = domains[i];
398         }
399     }
400 
ToLogRemoveRqstOHOS::HiviewDFX::HilogArgs401     void ToLogRemoveRqst(LogRemoveRqst& rqst)
402     {
403         rqst.types = types;
404     }
405 };
406 
407 using OptHandler = std::function<int(HilogArgs& context, const char *arg)>;
408 
QueryLogHandler(HilogArgs & context,const char * arg)409 static int QueryLogHandler(HilogArgs& context, const char *arg)
410 {
411     OutputRqst rqst = { 0 };
412     context.ToOutputRqst(rqst);
413     LogIoctl ioctl(IoctlCmd::OUTPUT_RQST, IoctlCmd::OUTPUT_RSP);
414     int ret = ioctl.RequestOutput(rqst, [&context](const OutputRsp& rsp) {
415         if (rsp.end) {
416             return RET_SUCCESS;
417         }
418         LogContent content = {
419             .level = rsp.level,
420             .type = rsp.type,
421             .pid = rsp.pid,
422             .tid = rsp.tid,
423             .domain = rsp.domain,
424             .tv_sec = rsp.tv_sec,
425             .tv_nsec = rsp.tv_nsec,
426             .mono_sec = rsp.mono_sec,
427             .tag = rsp.data,
428             .log = (rsp.data + rsp.tagLen)
429         };
430         LogFormat format = {
431             .colorful = context.colorful,
432             .timeFormat = ((context.timeFormat == FormatTime::INVALID) ? FormatTime::TIME : context.timeFormat),
433             .timeAccuFormat =
434                 ((context.timeAccuFormat == FormatTimeAccu::INVALID) ? FormatTimeAccu::MSEC : context.timeAccuFormat),
435             .year = context.year,
436             .zone = context.zone,
437             .wrap = context.wrap
438         };
439         LogPrintWithFormat(content, format);
440         return static_cast<int>(SUCCESS_CONTINUE);
441     });
442     if (ret != RET_SUCCESS) {
443         return ret;
444     }
445     return RET_SUCCESS;
446 }
447 
HeadHandler(HilogArgs & context,const char * arg)448 static int HeadHandler(HilogArgs& context, const char *arg)
449 {
450     if (IsNumericStr(arg) == false) {
451         return ERR_NOT_NUMBER_STR;
452     }
453     int lines = 0;
454     (void)StrToInt(arg, lines);
455     context.headLines = static_cast<uint16_t>(lines);
456     context.noBlock = true; // don't block implicitly
457     return QueryLogHandler(context, arg);
458 }
459 
BaseLogLevelHandler(HilogArgs & context,const char * arg)460 static int BaseLogLevelHandler(HilogArgs& context, const char *arg)
461 {
462     uint16_t baseLevel = PrettyStr2LogLevel(arg);
463     if (baseLevel == LOG_LEVEL_MIN) {
464         return ERR_LOG_LEVEL_INVALID;
465     }
466     context.baseLevel = baseLevel;
467     int ret;
468     if (context.domainCount == 0 && context.tagCount == 0) {
469         ret = SetGlobalLevel(context.baseLevel);
470         PrintResult(ret, (string("Set global log level to ") + arg));
471     }
472     if (context.domainCount != 0) {
473         for (int i = 0; i < context.domainCount; i++) {
474             ret = SetDomainLevel(context.domains[i], context.baseLevel);
475             PrintResult(ret, (string("Set domain 0x") + Uint2HexStr(context.domains[i]) +  " log level to " + arg));
476         }
477     }
478     if (context.tagCount != 0) {
479         for (int i = 0; i < context.tagCount; i++) {
480             ret = SetTagLevel(context.tags[i], context.baseLevel);
481             PrintResult(ret, (string("Set tag ") + context.tags[i] +  " log level to " + arg));
482         }
483     }
484     return RET_SUCCESS;
485 }
486 
487 static constexpr char BLACK_PREFIX = '^';
DomainHandler(HilogArgs & context,const char * arg)488 static int DomainHandler(HilogArgs& context, const char *arg)
489 {
490     context.blackDomain = (arg[0] == BLACK_PREFIX);
491     std::vector<std::string> domains;
492     Split(context.blackDomain ? arg + 1 : arg, domains);
493     if (domains.size() == 0) {
494         return ERR_INVALID_ARGUMENT;
495     }
496     int index = 0;
497     for (string d : domains) {
498         if (index >= MAX_DOMAINS) {
499             return ERR_TOO_MANY_DOMAINS;
500         }
501         uint32_t domain = HexStr2Uint(d);
502         if (domain == 0) {
503             return ERR_INVALID_DOMAIN_STR;
504         }
505         context.domains[index++] = domain;
506     }
507     context.domainCount = index;
508     return RET_SUCCESS;
509 }
510 
RegexHandler(HilogArgs & context,const char * arg)511 static int RegexHandler(HilogArgs& context, const char *arg)
512 {
513     context.regex = arg;
514     if (context.regex.length() >= MAX_REGEX_STR_LEN) {
515         return ERR_REGEX_STR_TOO_LONG;
516     }
517     return RET_SUCCESS;
518 }
519 
FileNameHandler(HilogArgs & context,const char * arg)520 static int FileNameHandler(HilogArgs& context, const char *arg)
521 {
522     context.fileName = arg;
523     if (context.fileName.length() >= MAX_FILE_NAME_LEN) {
524         return ERR_FILE_NAME_TOO_LONG;
525     }
526     return RET_SUCCESS;
527 }
528 
BufferSizeGetHandler(HilogArgs & context,const char * arg)529 static int BufferSizeGetHandler(HilogArgs& context, const char *arg)
530 {
531     BufferSizeGetRqst rqst = { 0 };
532     context.ToBufferSizeGetRqst(rqst);
533     LogIoctl ioctl(IoctlCmd::BUFFERSIZE_GET_RQST, IoctlCmd::BUFFERSIZE_GET_RSP);
534     int ret = ioctl.Request<BufferSizeGetRqst, BufferSizeGetRsp>(rqst, [&rqst](const BufferSizeGetRsp& rsp) {
535         for (uint16_t i = 0; i < static_cast<uint16_t>(LOG_TYPE_MAX); i++) {
536             if (rsp.size[i] > 0) {
537                 cout << "Log type " << LogType2Str(i) << " buffer size is " << Size2Str(rsp.size[i]) << endl;
538             }
539         }
540         return RET_SUCCESS;
541     });
542     if (ret != RET_SUCCESS) {
543         cout << "Get " << ComboLogType2Str(rqst.types) << " buffer size failed" << endl;
544     }
545     return ret;
546 }
547 
BufferSizeSetHandler(HilogArgs & context,const char * arg)548 static int BufferSizeSetHandler(HilogArgs& context, const char *arg)
549 {
550     uint64_t size = Str2Size(arg);
551     if (size == 0) {
552         return ERR_INVALID_SIZE_STR;
553     }
554     context.buffSize = static_cast<int32_t>(size);
555     BufferSizeSetRqst rqst;
556     context.ToBufferSizeSetRqst(rqst);
557     LogIoctl ioctl(IoctlCmd::BUFFERSIZE_SET_RQST, IoctlCmd::BUFFERSIZE_SET_RSP);
558     int ret = ioctl.Request<BufferSizeSetRqst, BufferSizeSetRsp>(rqst, [&rqst](const BufferSizeSetRsp& rsp) {
559         for (uint16_t i = 0; i < static_cast<uint16_t>(LOG_TYPE_MAX); i++) {
560             if (rsp.size[i] > 0) {
561                 cout << "Set log type " << LogType2Str(i) << " buffer size to "
562                 << Size2Str(rsp.size[i]) << " successfully" << endl;
563             } else if (rsp.size[i] < 0) {
564                 cout << "Set log type " << LogType2Str(i) << " buffer size to "
565                 << Size2Str(rqst.size) << " failed" << endl;
566                 PrintErr(rsp.size[i]);
567             }
568         }
569         return RET_SUCCESS;
570     });
571     if (ret != RET_SUCCESS) {
572         cout << "Set buffer size failed" << endl;
573     }
574     return ret;
575 }
576 
HelpHandler(HilogArgs & context,const char * arg)577 static int HelpHandler(HilogArgs& context, const char *arg)
578 {
579     Helper("");
580     return RET_SUCCESS;
581 }
582 
JobIdHandler(HilogArgs & context,const char * arg)583 static int JobIdHandler(HilogArgs& context, const char *arg)
584 {
585     if (IsNumericStr(arg) == false) {
586         return ERR_NOT_NUMBER_STR;
587     }
588     int jobId = 0;
589     (void)StrToInt(arg, jobId);
590     context.jobId = static_cast<uint32_t>(jobId);
591     return RET_SUCCESS;
592 }
593 
594 static const string FEATURE_ON = "on";
595 static const string FEATURE_OFF = "off";
KmsgFeatureSetHandler(HilogArgs & context,const char * arg)596 static int KmsgFeatureSetHandler(HilogArgs& context, const char *arg)
597 {
598     string argStr = arg;
599     bool kmsgOn = true;
600     if (argStr == FEATURE_ON) {
601         kmsgOn = true;
602     } else if (argStr == FEATURE_OFF) {
603         kmsgOn = false;
604     } else {
605         return ERR_INVALID_ARGUMENT;
606     }
607     KmsgEnableRqst rqst = { kmsgOn };
608     LogIoctl ioctl(IoctlCmd::KMSG_ENABLE_RQST, IoctlCmd::KMSG_ENABLE_RSP);
609     int ret = ioctl.Request<KmsgEnableRqst, KmsgEnableRsp>(rqst, [&rqst](const KmsgEnableRsp& rsp) {
610         return RET_SUCCESS;
611     });
612     PrintResult(ret, (string("Set hilogd storing kmsg log ") + arg));
613     return ret;
614 }
615 
FileLengthHandler(HilogArgs & context,const char * arg)616 static int FileLengthHandler(HilogArgs& context, const char *arg)
617 {
618     uint64_t size = Str2Size(arg);
619     if (size == 0) {
620         return ERR_INVALID_SIZE_STR;
621     }
622     context.fileSize = size;
623     return RET_SUCCESS;
624 }
625 
LevelHandler(HilogArgs & context,const char * arg)626 static int LevelHandler(HilogArgs& context, const char *arg)
627 {
628     uint16_t levels = Str2ComboLogLevel(arg);
629     if (levels == 0) {
630         return ERR_LOG_LEVEL_INVALID;
631     }
632     context.levels = levels;
633     return RET_SUCCESS;
634 }
635 
FileCompressHandler(HilogArgs & context,const char * arg)636 static int FileCompressHandler(HilogArgs& context, const char *arg)
637 {
638     context.stream = arg;
639     return RET_SUCCESS;
640 }
641 
FileNumberHandler(HilogArgs & context,const char * arg)642 static int FileNumberHandler(HilogArgs& context, const char *arg)
643 {
644     if (IsNumericStr(arg) == false) {
645         return ERR_NOT_NUMBER_STR;
646     }
647     int fileNum = 0;
648     (void)StrToInt(arg, fileNum);
649     context.fileNum = static_cast<uint16_t>(fileNum);
650     return RET_SUCCESS;
651 }
652 
PrivateFeatureSetHandler(HilogArgs & context,const char * arg)653 static int PrivateFeatureSetHandler(HilogArgs& context, const char *arg)
654 {
655     string argStr = arg;
656     bool privateOn = true;
657     if (argStr == FEATURE_ON) {
658         privateOn = true;
659     } else if (argStr == FEATURE_OFF) {
660         privateOn = false;
661     } else {
662         return ERR_INVALID_ARGUMENT;
663     }
664     int ret = SetPrivateSwitchOn(privateOn);
665     PrintResult(ret, (string("Set hilog privacy format ") + arg));
666     return RET_SUCCESS;
667 }
668 
PidHandler(HilogArgs & context,const char * arg)669 static int PidHandler(HilogArgs& context, const char *arg)
670 {
671     context.blackPid = (arg[0] == BLACK_PREFIX);
672     std::vector<std::string> pids;
673     Split(context.blackPid ? arg + 1 : arg, pids);
674     if (pids.size() == 0) {
675         return ERR_INVALID_ARGUMENT;
676     }
677     int index = 0;
678     for (string p : pids) {
679         if (index >= MAX_PIDS) {
680             return ERR_TOO_MANY_PIDS;
681         }
682         if (IsNumericStr(p) == false) {
683             return ERR_NOT_NUMBER_STR;
684         }
685         int pid = 0;
686         (void)StrToInt(p, pid);
687         context.pids[index++] = static_cast<uint32_t>(pid);
688     }
689     context.pidCount = index;
690     return RET_SUCCESS;
691 }
692 
SetDomainFlowCtrl(bool on)693 static int SetDomainFlowCtrl(bool on)
694 {
695     DomainFlowCtrlRqst rqst = { 0 };
696     rqst.on = on;
697     LogIoctl ioctl(IoctlCmd::DOMAIN_FLOWCTRL_RQST, IoctlCmd::DOMAIN_FLOWCTRL_RSP);
698     int ret = ioctl.Request<DomainFlowCtrlRqst, DomainFlowCtrlRsp>(rqst, [&rqst](const DomainFlowCtrlRsp& rsp) {
699         return RET_SUCCESS;
700     });
701     return ret;
702 }
FlowControlFeatureSetHandler(HilogArgs & context,const char * arg)703 static int FlowControlFeatureSetHandler(HilogArgs& context, const char *arg)
704 {
705     string pid = "pid";
706     string domain = "domain";
707     string argStr = arg;
708     int ret;
709     if (argStr == (pid + FEATURE_ON)) {
710         ret = SetProcessSwitchOn(true);
711         cout << "Set flow control by process to enabled, result: " << ErrorCode2Str(ret) << endl;
712     } else if (argStr == (pid + FEATURE_OFF)) {
713         ret = SetProcessSwitchOn(false);
714         cout << "Set flow control by process to disabled, result: " << ErrorCode2Str(ret) << endl;
715     } else if (argStr == (domain + FEATURE_ON)) {
716         ret = SetDomainFlowCtrl(true);
717         cout << "Set flow control by domain to enabled, result: " << ErrorCode2Str(ret) << endl;
718     } else if (argStr == (domain + FEATURE_OFF)) {
719         ret = SetDomainFlowCtrl(false);
720         cout << "Set flow control by domain to disabled, result: " << ErrorCode2Str(ret) << endl;
721     } else {
722         return ERR_INVALID_ARGUMENT;
723     }
724     return ret;
725 }
726 
RemoveHandler(HilogArgs & context,const char * arg)727 static int RemoveHandler(HilogArgs& context, const char *arg)
728 {
729     LogRemoveRqst rqst = { 0 };
730     context.ToLogRemoveRqst(rqst);
731     LogIoctl ioctl(IoctlCmd::LOG_REMOVE_RQST, IoctlCmd::LOG_REMOVE_RSP);
732     int ret = ioctl.Request<LogRemoveRqst, LogRemoveRsp>(rqst, [&rqst](const LogRemoveRsp& rsp) {
733         cout << "Log type " << ComboLogType2Str(rsp.types) << " buffer clear successfully" << endl;
734         return RET_SUCCESS;
735     });
736     if (ret != RET_SUCCESS) {
737         cout << "Log buffer clear failed" << endl;
738     }
739     return ret;
740 }
741 
StatsInfoQueryHandler(HilogArgs & context,const char * arg)742 static int StatsInfoQueryHandler(HilogArgs& context, const char *arg)
743 {
744     StatsQueryRqst rqst = { 0 };
745     context.ToStatsQueryRqst(rqst);
746     LogIoctl ioctl(IoctlCmd::STATS_QUERY_RQST, IoctlCmd::STATS_QUERY_RSP);
747     int ret = ioctl.RequestStatsQuery(rqst, [&rqst](const StatsQueryRsp& rsp) {
748         HilogShowLogStatsInfo(rsp);
749         return RET_SUCCESS;
750     });
751     if (ret != RET_SUCCESS) {
752         cout << "Statistic info query failed" << endl;
753     }
754     return ret;
755 }
756 
StatsInfoClearHandler(HilogArgs & context,const char * arg)757 static int StatsInfoClearHandler(HilogArgs& context, const char *arg)
758 {
759     StatsClearRqst rqst = { 0 };
760     LogIoctl ioctl(IoctlCmd::STATS_CLEAR_RQST, IoctlCmd::STATS_CLEAR_RSP);
761     int ret = ioctl.Request<StatsClearRqst, StatsClearRsp>(rqst, [&rqst](const StatsClearRsp& rsp) {
762         cout << "Statistic info clear successfully" << endl;
763         return RET_SUCCESS;
764     });
765     if (ret != RET_SUCCESS) {
766         cout << "Statistic info clear failed" << endl;
767     }
768     return ret;
769 }
770 
TypeHandler(HilogArgs & context,const char * arg)771 static int TypeHandler(HilogArgs& context, const char *arg)
772 {
773     uint16_t types = Str2ComboLogType(arg);
774     if (types == 0) {
775         return ERR_LOG_TYPE_INVALID;
776     }
777     context.types = types;
778     return RET_SUCCESS;
779 }
780 
TagHandler(HilogArgs & context,const char * arg)781 static int TagHandler(HilogArgs& context, const char *arg)
782 {
783     context.blackTag = (arg[0] == BLACK_PREFIX);
784     std::vector<std::string> tags;
785     Split(context.blackTag ? arg + 1 : arg, tags);
786     int index = 0;
787     for (string t : tags) {
788         if (index >= MAX_TAGS) {
789             return ERR_TOO_MANY_TAGS;
790         }
791         if (t.length() >= MAX_TAG_LEN) {
792             return ERR_TAG_STR_TOO_LONG;
793         }
794         context.tags[index++] = t;
795     }
796     context.tagCount = index;
797     return RET_SUCCESS;
798 }
799 
TimeHandler(HilogArgs & context,FormatTime value)800 static int TimeHandler(HilogArgs& context, FormatTime value)
801 {
802     if (context.timeFormat != FormatTime::INVALID) {
803         return ERR_DUPLICATE_OPTION;
804     }
805     context.timeFormat = value;
806     return RET_SUCCESS;
807 }
808 
TimeAccuHandler(HilogArgs & context,FormatTimeAccu value)809 static int TimeAccuHandler(HilogArgs& context, FormatTimeAccu value)
810 {
811     if (context.timeAccuFormat != FormatTimeAccu::INVALID) {
812         return ERR_DUPLICATE_OPTION;
813     }
814     context.timeAccuFormat = value;
815     return RET_SUCCESS;
816 }
817 
FormatHandler(HilogArgs & context,const char * arg)818 static int FormatHandler(HilogArgs& context, const char *arg)
819 {
820     static std::unordered_map<std::string, std::function<int(HilogArgs&, int)>> handlers = {
821         {"color", [] (HilogArgs& context, int value) {
822             context.colorful = true;
823             return RET_SUCCESS;
824         }},
825         {"colour", [] (HilogArgs& context, int value) {
826             context.colorful = true;
827             return RET_SUCCESS;
828         }},
829         {"time", [] (HilogArgs& context, int value) {
830             return TimeHandler(context, FormatTime::TIME);
831         }},
832         {"epoch", [] (HilogArgs& context, int value) {
833             return TimeHandler(context, FormatTime::EPOCH);
834         }},
835         {"monotonic", [] (HilogArgs& context, int value) {
836             return TimeHandler(context, FormatTime::MONOTONIC);
837         }},
838         {"msec", [] (HilogArgs& context, int value) {
839             return TimeAccuHandler(context, FormatTimeAccu::MSEC);
840         }},
841         {"usec", [] (HilogArgs& context, int value) {
842             return TimeAccuHandler(context, FormatTimeAccu::USEC);
843         }},
844         {"nsec", [] (HilogArgs& context, int value) {
845             return TimeAccuHandler(context, FormatTimeAccu::NSEC);
846         }},
847         {"year", [] (HilogArgs& context, int value) {
848             context.year = true;
849             return RET_SUCCESS;
850         }},
851         {"zone", [] (HilogArgs& context, int value) {
852             context.zone = true;
853             tzset();
854             return RET_SUCCESS;
855         }},
856         {"wrap", [] (HilogArgs& context, int value) {
857             context.wrap = true;
858             return RET_SUCCESS;
859         }},
860     };
861 
862     auto handler = handlers.find(arg);
863     if (handler == handlers.end() || handler->second == nullptr) {
864         return ERR_INVALID_ARGUMENT;
865     }
866     return handler->second(context, 0);
867 }
868 
PersistTaskStart(HilogArgs & context)869 static int PersistTaskStart(HilogArgs& context)
870 {
871     PersistStartRqst rqst = { { 0 }, 0 };
872     context.ToPersistStartRqst(rqst);
873     LogIoctl ioctl(IoctlCmd::PERSIST_START_RQST, IoctlCmd::PERSIST_START_RSP);
874     int ret = ioctl.Request<PersistStartRqst, PersistStartRsp>(rqst, [&rqst](const PersistStartRsp& rsp) {
875         cout << "Persist task [jobid:" << rsp.jobId << "] start successfully" << endl;
876         return RET_SUCCESS;
877     });
878     if (ret != RET_SUCCESS) {
879         cout << "Persist task start failed" << endl;
880     }
881     return ret;
882 }
883 
PersistTaskStop(HilogArgs & context)884 static int PersistTaskStop(HilogArgs& context)
885 {
886     PersistStopRqst rqst = { 0 };
887     context.ToPersistStopRqst(rqst);
888     LogIoctl ioctl(IoctlCmd::PERSIST_STOP_RQST, IoctlCmd::PERSIST_STOP_RSP);
889     int ret = ioctl.Request<PersistStopRqst, PersistStopRsp>(rqst,  [&rqst](const PersistStopRsp& rsp) {
890         for (int i = 0; i < rsp.jobNum; i++) {
891             cout << "Persist task [jobid:" << rsp.jobId[i] << "] stop successfully" << endl;
892         }
893         return RET_SUCCESS;
894     });
895     if (ret != RET_SUCCESS) {
896         cout << "Persist task stop failed" << endl;
897     }
898     return ret;
899 }
900 
PrintTaskInfo(const PersistTaskInfo & task)901 static void PrintTaskInfo(const PersistTaskInfo& task)
902 {
903     cout << task.jobId << " " << ComboLogType2Str(task.outputFilter.types) << " " << task.stream << " ";
904     cout << task.fileName << " " << Size2Str(task.fileSize) << " " << to_string(task.fileNum) << endl;
905 }
906 
PersistTaskQuery()907 static int PersistTaskQuery()
908 {
909     PersistQueryRqst rqst = { 0 };
910     LogIoctl ioctl(IoctlCmd::PERSIST_QUERY_RQST, IoctlCmd::PERSIST_QUERY_RSP);
911     int ret = ioctl.Request<PersistQueryRqst, PersistQueryRsp>(rqst,  [&rqst](const PersistQueryRsp& rsp) {
912         for (int i = 0; i < rsp.jobNum; i++) {
913             PrintTaskInfo(rsp.taskInfo[i]);
914         }
915         return RET_SUCCESS;
916     });
917     if (ret != RET_SUCCESS) {
918         cout << "Persist task query failed" << endl;
919     }
920     return ret;
921 }
922 
PersistTaskRefresh()923 static int PersistTaskRefresh()
924 {
925     PersistRefreshRqst rqst = { 0 };
926     LogIoctl ioctl(IoctlCmd::PERSIST_REFRESH_RQST, IoctlCmd::PERSIST_REFRESH_RSP);
927     int ret = ioctl.Request<PersistRefreshRqst, PersistRefreshRsp>(rqst, [&rqst](const PersistRefreshRsp& rsp) {
928         for (int i = 0; i < rsp.jobNum; i++) {
929             PrintResult(RET_SUCCESS, (string("Persist task [jobid:") + to_string(rsp.jobId[i]) + "] refresh"));
930         }
931         return RET_SUCCESS;
932     });
933     if (ret != RET_SUCCESS) {
934         PrintResult(RET_FAIL, (string("Persist task refresh")));
935     }
936     return ret;
937 }
938 
ClearPersistLog()939 static int ClearPersistLog()
940 {
941     PersistClearRqst rqst = { 0 };
942     LogIoctl ioctl(IoctlCmd::PERSIST_CLEAR_RQST, IoctlCmd::PERSIST_CLEAR_RSP);
943     int ret = ioctl.Request<PersistClearRqst, PersistClearRsp>(rqst, [&rqst](const PersistClearRsp& rsp) {
944         PrintResult(RET_SUCCESS, (string("Persist log /data/log/hilog clear")));
945         return RET_SUCCESS;
946     });
947     if (ret != RET_SUCCESS) {
948         PrintResult(RET_FAIL, (string("Persist log /data/log/hilog clear")));
949     }
950     return ret;
951 }
952 
PersistTaskHandler(HilogArgs & context,const char * arg)953 static int PersistTaskHandler(HilogArgs& context, const char *arg)
954 {
955     string strArg = arg;
956     if (strArg == "start") {
957         return PersistTaskStart(context);
958     } else if (strArg == "stop") {
959         return PersistTaskStop(context);
960     } else if (strArg == "query") {
961         return PersistTaskQuery();
962     } else if (strArg == "refresh") {
963         return PersistTaskRefresh();
964     } else if (strArg == "clear") {
965         return ClearPersistLog();
966     } else {
967         return ERR_INVALID_ARGUMENT;
968     }
969     return RET_SUCCESS;
970 }
971 
NoBlockHandler(HilogArgs & context,const char * arg)972 static int NoBlockHandler(HilogArgs& context, const char *arg)
973 {
974     context.noBlock = true;
975     return QueryLogHandler(context, arg);
976 }
977 
TailHandler(HilogArgs & context,const char * arg)978 static int TailHandler(HilogArgs& context, const char *arg)
979 {
980     if (IsNumericStr(arg) == false) {
981         return ERR_NOT_NUMBER_STR;
982     }
983     int tailLines = 0;
984     (void)StrToInt(arg, tailLines);
985     context.tailLines = static_cast<uint16_t>(tailLines);
986     context.noBlock = true; // don't block implicitly
987     return QueryLogHandler(context, arg);
988 }
989 
990 struct OptEntry {
991     const char opt;
992     const char *longOpt;
993     const ControlCmd cmd;
994     const OptHandler handler;
995     const bool needArg;
996     // how many times can this option be used, for example:
997     //   hilog -v msec -v color ...
998     uint32_t count;
999 };
1000 static OptEntry optEntries[] = {
1001     {'a', "head", ControlCmd::CMD_QUERY, HeadHandler, true, 1},
1002     {'b', "baselevel", ControlCmd::CMD_LOGLEVEL_SET, BaseLogLevelHandler, true, 1},
1003     {'D', "domain", ControlCmd::NOT_CMD, DomainHandler, true, 1},
1004     {'e', "regex", ControlCmd::NOT_CMD, RegexHandler, true, 1},
1005     {'f', "filename", ControlCmd::NOT_CMD, FileNameHandler, true, 1},
1006     {'g', nullptr, ControlCmd::CMD_BUFFER_SIZE_QUERY, BufferSizeGetHandler, false, 1},
1007     {'G', "buffer-size", ControlCmd::CMD_BUFFER_SIZE_SET, BufferSizeSetHandler, true, 1},
1008     {'h', "help", ControlCmd::CMD_HELP, HelpHandler, false, 1},
1009     {'j', "jobid", ControlCmd::NOT_CMD, JobIdHandler, true, 1},
1010     {'k', "kmsg", ControlCmd::CMD_KMSG_FEATURE_SET, KmsgFeatureSetHandler, true, 1},
1011     {'l', "length", ControlCmd::NOT_CMD, FileLengthHandler, true, 1},
1012     {'L', "level", ControlCmd::NOT_CMD, LevelHandler, true, 1},
1013     {'m', "stream", ControlCmd::NOT_CMD, FileCompressHandler, true, 1},
1014     {'n', "number", ControlCmd::NOT_CMD, FileNumberHandler, true, 1},
1015     {'p', "private", ControlCmd::CMD_PRIVATE_FEATURE_SET, PrivateFeatureSetHandler, true, 1},
1016     {'P', "pid", ControlCmd::NOT_CMD, PidHandler, true, 1},
1017     {'Q', "flowctrl", ControlCmd::CMD_FLOWCONTROL_FEATURE_SET, FlowControlFeatureSetHandler, true, 1},
1018     {'r', nullptr, ControlCmd::CMD_REMOVE, RemoveHandler, false, 1},
1019     {'s', "statistics", ControlCmd::CMD_STATS_INFO_QUERY, StatsInfoQueryHandler, false, 1},
1020     {'S', nullptr, ControlCmd::CMD_STATS_INFO_CLEAR, StatsInfoClearHandler, false, 1},
1021     {'t', "type", ControlCmd::NOT_CMD, TypeHandler, true, 1},
1022     {'T', "tag", ControlCmd::NOT_CMD, TagHandler, true, 1},
1023     {'v', "format", ControlCmd::NOT_CMD, FormatHandler, true, 5},
1024     {'w', "write", ControlCmd::CMD_PERSIST_TASK, PersistTaskHandler, true, 1},
1025     {'x', "exit", ControlCmd::CMD_QUERY, NoBlockHandler, false, 1},
1026     {'z', "tail", ControlCmd::CMD_QUERY, TailHandler, true, 1},
1027     {0, nullptr, ControlCmd::NOT_CMD, nullptr, false, 1}, // End default entry
1028 }; // "hxz:grsSa:v:e:t:L:G:f:l:n:j:w:p:k:D:T:b:Q:m:P:"
1029 static constexpr int OPT_ENTRY_CNT = sizeof(optEntries) / sizeof(OptEntry);
1030 
GetOpts(string & opts,struct option (& longOptions)[OPT_ENTRY_CNT])1031 static void GetOpts(string& opts, struct option(&longOptions)[OPT_ENTRY_CNT])
1032 {
1033     int longOptcount = 0;
1034     opts = "";
1035     int i;
1036     for (i = 0; i < OPT_ENTRY_CNT; i++) {
1037         if (optEntries[i].opt == 0) {
1038             break;
1039         }
1040         // opts
1041         opts += optEntries[i].opt;
1042         if (optEntries[i].needArg) {
1043             opts += ':';
1044         }
1045         // long option
1046         if (optEntries[i].longOpt == nullptr) {
1047             continue;
1048         }
1049         longOptions[longOptcount].name = optEntries[i].longOpt;
1050         longOptions[longOptcount].has_arg = optEntries[i].needArg ? required_argument : no_argument;
1051         longOptions[longOptcount].flag = nullptr;
1052         longOptions[longOptcount].val = optEntries[i].opt;
1053         longOptcount++;
1054     }
1055     longOptions[longOptcount].name = nullptr;
1056     longOptions[longOptcount].has_arg = 0;
1057     longOptions[longOptcount].flag = nullptr;
1058     longOptions[longOptcount].val = 0;
1059     return;
1060 }
1061 
GetOptEntry(int choice)1062 static OptEntry* GetOptEntry(int choice)
1063 {
1064     OptEntry *entry = &(optEntries[OPT_ENTRY_CNT - 1]);
1065     int i = 0;
1066     for (i = 0; i < OPT_ENTRY_CNT; i++) {
1067         if (optEntries[i].opt == static_cast<char>(choice)) {
1068             entry = &(optEntries[i]);
1069             break;
1070         }
1071     }
1072     return entry;
1073 }
1074 
HilogEntry(int argc,char * argv[])1075 int HilogEntry(int argc, char* argv[])
1076 {
1077     struct option longOptions[OPT_ENTRY_CNT];
1078     string opts;
1079     GetOpts(opts, longOptions);
1080     HilogArgs context;
1081     int optIndex = 0;
1082 
1083     // 0. help has special case
1084     static const int argCountHelp = 3;
1085     if (argc == argCountHelp) {
1086         string arg = argv[1];
1087         if (arg == "--help" || arg == "-h") {
1088             Helper(argv[argCountHelp - 1]);
1089             return RET_SUCCESS;
1090         }
1091     }
1092     // 1. Scan all options and process NOT_CMD options' arguments
1093     int cmdCount = 0;
1094     OptEntry queryEntry =  {' ', "", ControlCmd::CMD_QUERY, QueryLogHandler, false, 0};
1095     OptEntry *cmdEntry = &queryEntry; // No cmd means CMD_QUERY cmd
1096     string cmdArgs = "";
1097     while (1) {
1098         int choice = getopt_long(argc, argv, opts.c_str(), longOptions, &optIndex);
1099         if (choice == -1) {
1100             break;
1101         }
1102         if (choice == '?') {
1103             return RET_FAIL;
1104         }
1105         OptEntry *entry = GetOptEntry(choice);
1106         if (optind < argc && argv[optind][0] != '-') { // all options need only 1 argument
1107             PrintErr(ERR_TOO_MANY_ARGUMENTS);
1108             return ERR_TOO_MANY_ARGUMENTS;
1109         }
1110         if (entry->count == 0) {
1111             PrintErr(ERR_DUPLICATE_OPTION);
1112             return ERR_DUPLICATE_OPTION;
1113         }
1114         entry->count--;
1115         if (entry->cmd == ControlCmd::NOT_CMD) {
1116             int ret = entry->handler(context, optarg);
1117             if (ret != RET_SUCCESS) {
1118                 PrintErr(ret);
1119                 return ret;
1120             } else {
1121                 continue;
1122             }
1123         }
1124         cmdEntry = entry;
1125         cmdCount++;
1126         if (optarg != nullptr) {
1127             cmdArgs = optarg;
1128         }
1129     }
1130     if (cmdCount > 1) {
1131         cerr << ErrorCode2Str(ERR_COMMAND_INVALID) << endl;
1132         return ERR_COMMAND_INVALID;
1133     }
1134     // 2. Process CMD_XXX
1135     int ret = cmdEntry->handler(context, cmdArgs.c_str());
1136     if (ret != RET_SUCCESS) {
1137         PrintErr(ret);
1138         return ret;
1139     }
1140     return RET_SUCCESS;
1141 }
1142 } // namespace HiviewDFX
1143 } // namespace OHOS
1144 
main(int argc,char * argv[])1145 int main(int argc, char* argv[])
1146 {
1147     (void)OHOS::HiviewDFX::HilogEntry(argc, argv);
1148     return 0;
1149 }
1150