cmdline: add alignment constraint
[dpdk.git] / lib / librte_cmdline / cmdline_parse.c
1 /*-
2  *   BSD LICENSE
3  *
4  *   Copyright(c) 2010-2014 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  *
7  *   Redistribution and use in source and binary forms, with or without
8  *   modification, are permitted provided that the following conditions
9  *   are met:
10  *
11  *     * Redistributions of source code must retain the above copyright
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright
14  *       notice, this list of conditions and the following disclaimer in
15  *       the documentation and/or other materials provided with the
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its
18  *       contributors may be used to endorse or promote products derived
19  *       from this software without specific prior written permission.
20  *
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 2009, Olivier MATZ <zer0@droids-corp.org>
36  * All rights reserved.
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions are met:
39  *
40  *     * Redistributions of source code must retain the above copyright
41  *       notice, this list of conditions and the following disclaimer.
42  *     * Redistributions in binary form must reproduce the above copyright
43  *       notice, this list of conditions and the following disclaimer in the
44  *       documentation and/or other materials provided with the distribution.
45  *     * Neither the name of the University of California, Berkeley nor the
46  *       names of its contributors may be used to endorse or promote products
47  *       derived from this software without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
50  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
51  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
52  * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
53  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
54  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
55  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
56  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
57  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
58  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
59  */
60
61 #include <stdio.h>
62 #include <stdarg.h>
63 #include <errno.h>
64 #include <string.h>
65 #include <inttypes.h>
66 #include <ctype.h>
67 #include <termios.h>
68
69 #include <netinet/in.h>
70
71 #include <rte_string_fns.h>
72
73 #include "cmdline_rdline.h"
74 #include "cmdline_parse.h"
75 #include "cmdline.h"
76
77 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
78 #define debug_printf printf
79 #else
80 #define debug_printf(args...) do {} while(0)
81 #endif
82
83 #define CMDLINE_BUFFER_SIZE 64
84
85 /* isblank() needs _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE, so use our
86  * own. */
87 static int
88 isblank2(char c)
89 {
90         if (c == ' ' ||
91             c == '\t' )
92                 return 1;
93         return 0;
94 }
95
96 static int
97 isendofline(char c)
98 {
99         if (c == '\n' ||
100             c == '\r' )
101                 return 1;
102         return 0;
103 }
104
105 static int
106 iscomment(char c)
107 {
108         if (c == '#')
109                 return 1;
110         return 0;
111 }
112
113 int
114 cmdline_isendoftoken(char c)
115 {
116         if (!c || iscomment(c) || isblank2(c) || isendofline(c))
117                 return 1;
118         return 0;
119 }
120
121 int
122 cmdline_isendofcommand(char c)
123 {
124         if (!c || iscomment(c) || isendofline(c))
125                 return 1;
126         return 0;
127 }
128
129 static unsigned int
130 nb_common_chars(const char * s1, const char * s2)
131 {
132         unsigned int i=0;
133
134         while (*s1==*s2 && *s1) {
135                 s1++;
136                 s2++;
137                 i++;
138         }
139         return i;
140 }
141
142 /**
143  * try to match the buffer with an instruction (only the first
144  * nb_match_token tokens if != 0). Return 0 if we match all the
145  * tokens, else the number of matched tokens, else -1.
146  */
147 static int
148 match_inst(cmdline_parse_inst_t *inst, const char *buf,
149            unsigned int nb_match_token, void *resbuf, unsigned resbuf_size,
150            cmdline_parse_token_hdr_t
151                 *(*dyn_tokens)[CMDLINE_PARSE_DYNAMIC_TOKENS])
152 {
153         unsigned int token_num=0;
154         cmdline_parse_token_hdr_t * token_p;
155         unsigned int i=0;
156         int n = 0;
157         struct cmdline_token_hdr token_hdr;
158
159         token_p = inst->tokens[token_num];
160         if (!token_p && dyn_tokens && inst->f) {
161                 if (!(*dyn_tokens)[0])
162                         inst->f(&(*dyn_tokens)[0], NULL, dyn_tokens);
163                 token_p = (*dyn_tokens)[0];
164         }
165         if (token_p)
166                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
167
168         /* check if we match all tokens of inst */
169         while (token_p && (!nb_match_token || i<nb_match_token)) {
170                 debug_printf("TK\n");
171                 /* skip spaces */
172                 while (isblank2(*buf)) {
173                         buf++;
174                 }
175
176                 /* end of buf */
177                 if ( isendofline(*buf) || iscomment(*buf) )
178                         break;
179
180                 if (resbuf == NULL) {
181                         n = token_hdr.ops->parse(token_p, buf, NULL, 0);
182                 } else {
183                         unsigned rb_sz;
184
185                         if (token_hdr.offset > resbuf_size) {
186                                 printf("Parse error(%s:%d): Token offset(%u) "
187                                         "exceeds maximum size(%u)\n",
188                                         __FILE__, __LINE__,
189                                         token_hdr.offset, resbuf_size);
190                                 return -ENOBUFS;
191                         }
192                         rb_sz = resbuf_size - token_hdr.offset;
193
194                         n = token_hdr.ops->parse(token_p, buf, (char *)resbuf +
195                                 token_hdr.offset, rb_sz);
196                 }
197
198                 if (n < 0)
199                         break;
200
201                 debug_printf("TK parsed (len=%d)\n", n);
202                 i++;
203                 buf += n;
204
205                 token_num ++;
206                 if (!inst->tokens[0]) {
207                         if (token_num < (CMDLINE_PARSE_DYNAMIC_TOKENS - 1)) {
208                                 if (!(*dyn_tokens)[token_num])
209                                         inst->f(&(*dyn_tokens)[token_num],
210                                                 NULL,
211                                                 dyn_tokens);
212                                 token_p = (*dyn_tokens)[token_num];
213                         } else
214                                 token_p = NULL;
215                 } else
216                         token_p = inst->tokens[token_num];
217                 if (token_p)
218                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
219         }
220
221         /* does not match */
222         if (i==0)
223                 return -1;
224
225         /* in case we want to match a specific num of token */
226         if (nb_match_token) {
227                 if (i == nb_match_token) {
228                         return 0;
229                 }
230                 return i;
231         }
232
233         /* we don't match all the tokens */
234         if (token_p) {
235                 return i;
236         }
237
238         /* are there are some tokens more */
239         while (isblank2(*buf)) {
240                 buf++;
241         }
242
243         /* end of buf */
244         if ( isendofline(*buf) || iscomment(*buf) )
245                 return 0;
246
247         /* garbage after inst */
248         return i;
249 }
250
251
252 int
253 cmdline_parse(struct cmdline *cl, const char * buf)
254 {
255         unsigned int inst_num=0;
256         cmdline_parse_inst_t *inst;
257         const char *curbuf;
258         union {
259                 char buf[CMDLINE_PARSE_RESULT_BUFSIZE];
260                 long double align; /* strong alignment constraint for buf */
261         } result;
262         cmdline_parse_token_hdr_t *dyn_tokens[CMDLINE_PARSE_DYNAMIC_TOKENS];
263         void (*f)(void *, struct cmdline *, void *) = NULL;
264         void *data = NULL;
265         int comment = 0;
266         int linelen = 0;
267         int parse_it = 0;
268         int err = CMDLINE_PARSE_NOMATCH;
269         int tok;
270         cmdline_parse_ctx_t *ctx;
271 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
272         char debug_buf[BUFSIZ];
273 #endif
274
275         if (!cl || !buf)
276                 return CMDLINE_PARSE_BAD_ARGS;
277
278         ctx = cl->ctx;
279         memset(&dyn_tokens, 0, sizeof(dyn_tokens));
280
281         /*
282          * - look if the buffer contains at least one line
283          * - look if line contains only spaces or comments
284          * - count line length
285          */
286         curbuf = buf;
287         while (! isendofline(*curbuf)) {
288                 if ( *curbuf == '\0' ) {
289                         debug_printf("Incomplete buf (len=%d)\n", linelen);
290                         return 0;
291                 }
292                 if ( iscomment(*curbuf) ) {
293                         comment = 1;
294                 }
295                 if ( ! isblank2(*curbuf) && ! comment) {
296                         parse_it = 1;
297                 }
298                 curbuf++;
299                 linelen++;
300         }
301
302         /* skip all endofline chars */
303         while (isendofline(buf[linelen])) {
304                 linelen++;
305         }
306
307         /* empty line */
308         if ( parse_it == 0 ) {
309                 debug_printf("Empty line (len=%d)\n", linelen);
310                 return linelen;
311         }
312
313 #ifdef RTE_LIBRTE_CMDLINE_DEBUG
314         snprintf(debug_buf, (linelen>64 ? 64 : linelen), "%s", buf);
315         debug_printf("Parse line : len=%d, <%s>\n", linelen, debug_buf);
316 #endif
317
318         /* parse it !! */
319         inst = ctx[inst_num];
320         while (inst) {
321                 debug_printf("INST %d\n", inst_num);
322
323                 /* fully parsed */
324                 tok = match_inst(inst, buf, 0, result.buf, sizeof(result.buf),
325                                  &dyn_tokens);
326
327                 if (tok > 0) /* we matched at least one token */
328                         err = CMDLINE_PARSE_BAD_ARGS;
329
330                 else if (!tok) {
331                         debug_printf("INST fully parsed\n");
332                         /* skip spaces */
333                         while (isblank2(*curbuf)) {
334                                 curbuf++;
335                         }
336
337                         /* if end of buf -> there is no garbage after inst */
338                         if (isendofline(*curbuf) || iscomment(*curbuf)) {
339                                 if (!f) {
340                                         memcpy(&f, &inst->f, sizeof(f));
341                                         memcpy(&data, &inst->data, sizeof(data));
342                                 }
343                                 else {
344                                         /* more than 1 inst matches */
345                                         err = CMDLINE_PARSE_AMBIGUOUS;
346                                         f=NULL;
347                                         debug_printf("Ambiguous cmd\n");
348                                         break;
349                                 }
350                         }
351                 }
352
353                 inst_num ++;
354                 inst = ctx[inst_num];
355         }
356
357         /* call func */
358         if (f) {
359                 f(result.buf, cl, data);
360         }
361
362         /* no match */
363         else {
364                 debug_printf("No match err=%d\n", err);
365                 return err;
366         }
367
368         return linelen;
369 }
370
371 int
372 cmdline_complete(struct cmdline *cl, const char *buf, int *state,
373                  char *dst, unsigned int size)
374 {
375         const char *partial_tok = buf;
376         unsigned int inst_num = 0;
377         cmdline_parse_inst_t *inst;
378         cmdline_parse_token_hdr_t *token_p;
379         struct cmdline_token_hdr token_hdr;
380         char tmpbuf[CMDLINE_BUFFER_SIZE], comp_buf[CMDLINE_BUFFER_SIZE];
381         cmdline_parse_token_hdr_t *dyn_tokens[CMDLINE_PARSE_DYNAMIC_TOKENS];
382         unsigned int partial_tok_len;
383         int comp_len = -1;
384         int tmp_len = -1;
385         int nb_token = 0;
386         unsigned int i, n;
387         int l;
388         unsigned int nb_completable;
389         unsigned int nb_non_completable;
390         int local_state = 0;
391         const char *help_str;
392         cmdline_parse_ctx_t *ctx;
393
394         if (!cl || !buf || !state || !dst)
395                 return -1;
396
397         ctx = cl->ctx;
398
399         debug_printf("%s called\n", __func__);
400         memset(&token_hdr, 0, sizeof(token_hdr));
401         memset(&dyn_tokens, 0, sizeof(dyn_tokens));
402
403         /* count the number of complete token to parse */
404         for (i=0 ; buf[i] ; i++) {
405                 if (!isblank2(buf[i]) && isblank2(buf[i+1]))
406                         nb_token++;
407                 if (isblank2(buf[i]) && !isblank2(buf[i+1]))
408                         partial_tok = buf+i+1;
409         }
410         partial_tok_len = strnlen(partial_tok, RDLINE_BUF_SIZE);
411
412         /* first call -> do a first pass */
413         if (*state <= 0) {
414                 debug_printf("try complete <%s>\n", buf);
415                 debug_printf("there is %d complete tokens, <%s> is incomplete\n",
416                              nb_token, partial_tok);
417
418                 nb_completable = 0;
419                 nb_non_completable = 0;
420
421                 inst = ctx[inst_num];
422                 while (inst) {
423                         /* parse the first tokens of the inst */
424                         if (nb_token &&
425                             match_inst(inst, buf, nb_token, NULL, 0,
426                                        &dyn_tokens))
427                                 goto next;
428
429                         debug_printf("instruction match\n");
430                         if (!inst->tokens[0]) {
431                                 if (nb_token <
432                                     (CMDLINE_PARSE_DYNAMIC_TOKENS - 1)) {
433                                         if (!dyn_tokens[nb_token])
434                                                 inst->f(&dyn_tokens[nb_token],
435                                                         NULL,
436                                                         &dyn_tokens);
437                                         token_p = dyn_tokens[nb_token];
438                                 } else
439                                         token_p = NULL;
440                         } else
441                                 token_p = inst->tokens[nb_token];
442                         if (token_p)
443                                 memcpy(&token_hdr, token_p, sizeof(token_hdr));
444
445                         /* non completable */
446                         if (!token_p ||
447                             !token_hdr.ops->complete_get_nb ||
448                             !token_hdr.ops->complete_get_elt ||
449                             (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
450                                 nb_non_completable++;
451                                 goto next;
452                         }
453
454                         debug_printf("%d choices for this token\n", n);
455                         for (i=0 ; i<n ; i++) {
456                                 if (token_hdr.ops->complete_get_elt(token_p, i,
457                                                                     tmpbuf,
458                                                                     sizeof(tmpbuf)) < 0)
459                                         continue;
460
461                                 /* we have at least room for one char */
462                                 tmp_len = strnlen(tmpbuf, sizeof(tmpbuf));
463                                 if (tmp_len < CMDLINE_BUFFER_SIZE - 1) {
464                                         tmpbuf[tmp_len] = ' ';
465                                         tmpbuf[tmp_len+1] = 0;
466                                 }
467
468                                 debug_printf("   choice <%s>\n", tmpbuf);
469
470                                 /* does the completion match the
471                                  * beginning of the word ? */
472                                 if (!strncmp(partial_tok, tmpbuf,
473                                              partial_tok_len)) {
474                                         if (comp_len == -1) {
475                                                 snprintf(comp_buf, sizeof(comp_buf),
476                                                          "%s", tmpbuf + partial_tok_len);
477                                                 comp_len =
478                                                         strnlen(tmpbuf + partial_tok_len,
479                                                                         sizeof(tmpbuf) - partial_tok_len);
480
481                                         }
482                                         else {
483                                                 comp_len =
484                                                         nb_common_chars(comp_buf,
485                                                                         tmpbuf+partial_tok_len);
486                                                 comp_buf[comp_len] = 0;
487                                         }
488                                         nb_completable++;
489                                 }
490                         }
491                 next:
492                         debug_printf("next\n");
493                         inst_num ++;
494                         inst = ctx[inst_num];
495                 }
496
497                 debug_printf("total choices %d for this completion\n",
498                              nb_completable);
499
500                 /* no possible completion */
501                 if (nb_completable == 0 && nb_non_completable == 0)
502                         return 0;
503
504                 /* if multichoice is not required */
505                 if (*state == 0 && partial_tok_len > 0) {
506                         /* one or several choices starting with the
507                            same chars */
508                         if (comp_len > 0) {
509                                 if ((unsigned)(comp_len + 1) > size)
510                                         return 0;
511
512                                 snprintf(dst, size, "%s", comp_buf);
513                                 dst[comp_len] = 0;
514                                 return 2;
515                         }
516                 }
517         }
518
519         /* init state correctly */
520         if (*state == -1)
521                 *state = 0;
522
523         debug_printf("Multiple choice STATE=%d\n", *state);
524
525         inst_num = 0;
526         inst = ctx[inst_num];
527         while (inst) {
528                 /* we need to redo it */
529                 inst = ctx[inst_num];
530
531                 if (nb_token &&
532                     match_inst(inst, buf, nb_token, NULL, 0, &dyn_tokens))
533                         goto next2;
534
535                 if (!inst->tokens[0]) {
536                         if (nb_token < (CMDLINE_PARSE_DYNAMIC_TOKENS - 1)) {
537                                 if (!dyn_tokens[nb_token])
538                                         inst->f(&dyn_tokens[nb_token],
539                                                 NULL,
540                                                 &dyn_tokens);
541                                 token_p = dyn_tokens[nb_token];
542                         } else
543                                 token_p = NULL;
544                 } else
545                         token_p = inst->tokens[nb_token];
546                 if (token_p)
547                         memcpy(&token_hdr, token_p, sizeof(token_hdr));
548
549                 /* one choice for this token */
550                 if (!token_p ||
551                     !token_hdr.ops->complete_get_nb ||
552                     !token_hdr.ops->complete_get_elt ||
553                     (n = token_hdr.ops->complete_get_nb(token_p)) == 0) {
554                         if (local_state < *state) {
555                                 local_state++;
556                                 goto next2;
557                         }
558                         (*state)++;
559                         if (token_p && token_hdr.ops->get_help) {
560                                 token_hdr.ops->get_help(token_p, tmpbuf,
561                                                         sizeof(tmpbuf));
562                                 help_str = inst->help_str;
563                                 if (help_str)
564                                         snprintf(dst, size, "[%s]: %s", tmpbuf,
565                                                  help_str);
566                                 else
567                                         snprintf(dst, size, "[%s]: No help",
568                                                  tmpbuf);
569                         }
570                         else {
571                                 snprintf(dst, size, "[RETURN]");
572                         }
573                         return 1;
574                 }
575
576                 /* several choices */
577                 for (i=0 ; i<n ; i++) {
578                         if (token_hdr.ops->complete_get_elt(token_p, i, tmpbuf,
579                                                             sizeof(tmpbuf)) < 0)
580                                 continue;
581                         /* we have at least room for one char */
582                         tmp_len = strnlen(tmpbuf, sizeof(tmpbuf));
583                         if (tmp_len < CMDLINE_BUFFER_SIZE - 1) {
584                                 tmpbuf[tmp_len] = ' ';
585                                 tmpbuf[tmp_len + 1] = 0;
586                         }
587
588                         debug_printf("   choice <%s>\n", tmpbuf);
589
590                         /* does the completion match the beginning of
591                          * the word ? */
592                         if (!strncmp(partial_tok, tmpbuf,
593                                      partial_tok_len)) {
594                                 if (local_state < *state) {
595                                         local_state++;
596                                         continue;
597                                 }
598                                 (*state)++;
599                                 l=snprintf(dst, size, "%s", tmpbuf);
600                                 if (l>=0 && token_hdr.ops->get_help) {
601                                         token_hdr.ops->get_help(token_p, tmpbuf,
602                                                                 sizeof(tmpbuf));
603                                         help_str = inst->help_str;
604                                         if (help_str)
605                                                 snprintf(dst+l, size-l, "[%s]: %s",
606                                                          tmpbuf, help_str);
607                                         else
608                                                 snprintf(dst+l, size-l,
609                                                          "[%s]: No help", tmpbuf);
610                                 }
611
612                                 return 1;
613                         }
614                 }
615         next2:
616                 inst_num ++;
617                 inst = ctx[inst_num];
618         }
619         return 0;
620 }