misc: fix issues reported by clang-15
[vpp.git] / src / vlib / cli.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * cli.c: command line interface
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #include <vlib/vlib.h>
41 #include <vlib/stats/stats.h>
42 #include <vlib/unix/unix.h>
43 #include <vppinfra/callback.h>
44 #include <vppinfra/cpu.h>
45 #include <vppinfra/elog.h>
46 #include <unistd.h>
47 #include <ctype.h>
48
49 /** \file src/vlib/cli.c Debug CLI Implementation
50  */
51
52 int vl_api_set_elog_trace_api_messages (int enable);
53 int vl_api_get_elog_trace_api_messages (void);
54
55 static void *current_traced_heap;
56
57 /* Root of all show commands. */
58 /* *INDENT-OFF* */
59 VLIB_CLI_COMMAND (vlib_cli_show_command, static) = {
60   .path = "show",
61   .short_help = "Show commands",
62 };
63 /* *INDENT-ON* */
64
65 /* Root of all clear commands. */
66 /* *INDENT-OFF* */
67 VLIB_CLI_COMMAND (vlib_cli_clear_command, static) = {
68   .path = "clear",
69   .short_help = "Clear commands",
70 };
71 /* *INDENT-ON* */
72
73 /* Root of all set commands. */
74 /* *INDENT-OFF* */
75 VLIB_CLI_COMMAND (vlib_cli_set_command, static) = {
76   .path = "set",
77   .short_help = "Set commands",
78 };
79 /* *INDENT-ON* */
80
81 /* Root of all test commands. */
82 /* *INDENT-OFF* */
83 VLIB_CLI_COMMAND (vlib_cli_test_command, static) = {
84   .path = "test",
85   .short_help = "Test commands",
86 };
87 /* *INDENT-ON* */
88
89 /* Returns bitmap of commands which match key. */
90 static uword *
91 vlib_cli_sub_command_match (vlib_cli_command_t * c, unformat_input_t * input)
92 {
93   int i, n;
94   uword *match = 0;
95   vlib_cli_parse_position_t *p;
96
97   unformat_skip_white_space (input);
98
99   for (i = 0;; i++)
100     {
101       uword k;
102
103       k = unformat_get_input (input);
104       switch (k)
105         {
106         case 'a' ... 'z':
107         case 'A' ... 'Z':
108         case '0' ... '9':
109         case '-':
110         case '_':
111           break;
112
113         case ' ':
114         case '\t':
115         case '\r':
116         case '\n':
117         case UNFORMAT_END_OF_INPUT:
118           /* White space or end of input removes any non-white
119              matches that were before possible. */
120           if (i < vec_len (c->sub_command_positions)
121               && clib_bitmap_count_set_bits (match) > 1)
122             {
123               p = vec_elt_at_index (c->sub_command_positions, i);
124               for (n = 0; n < vec_len (p->bitmaps); n++)
125                 match = clib_bitmap_andnot (match, p->bitmaps[n]);
126             }
127           goto done;
128
129         default:
130           unformat_put_input (input);
131           goto done;
132         }
133
134       if (i >= vec_len (c->sub_command_positions))
135         {
136         no_match:
137           clib_bitmap_free (match);
138           return 0;
139         }
140
141       p = vec_elt_at_index (c->sub_command_positions, i);
142       if (vec_len (p->bitmaps) == 0)
143         goto no_match;
144
145       n = k - p->min_char;
146       if (n < 0 || n >= vec_len (p->bitmaps))
147         goto no_match;
148
149       if (i == 0)
150         match = clib_bitmap_dup (p->bitmaps[n]);
151       else
152         match = clib_bitmap_and (match, p->bitmaps[n]);
153
154       if (clib_bitmap_is_zero (match))
155         goto no_match;
156     }
157
158 done:
159   return match;
160 }
161
162 uword
163 unformat_vlib_cli_line (unformat_input_t *i, va_list *va)
164 {
165   unformat_input_t *result = va_arg (*va, unformat_input_t *);
166   u8 *line = 0;
167   uword c;
168   int skip;
169
170 next_line:
171   skip = 0;
172
173   /* skip leading whitespace if any */
174   unformat_skip_white_space (i);
175
176   if (unformat_is_eof (i))
177     return 0;
178
179   while ((c = unformat_get_input (i)) != UNFORMAT_END_OF_INPUT)
180     {
181       if (c == '\\')
182         {
183           c = unformat_get_input (i);
184
185           if (c == '\n')
186             {
187               if (!skip)
188                 vec_add1 (line, '\n');
189               skip = 0;
190               continue;
191             }
192
193           if (!skip)
194             vec_add1 (line, '\\');
195
196           if (c == UNFORMAT_END_OF_INPUT)
197             break;
198
199           if (!skip)
200             vec_add1 (line, c);
201           continue;
202         }
203
204       if (c == '#')
205         skip = 1;
206       else if (c == '\n')
207         break;
208
209       if (!skip)
210         vec_add1 (line, c);
211     }
212
213   if (line == 0)
214     goto next_line;
215
216   unformat_init_vector (result, line);
217   return 1;
218 }
219
220 /* Looks for string based sub-input formatted { SUB-INPUT }. */
221 uword
222 unformat_vlib_cli_sub_input (unformat_input_t * i, va_list * args)
223 {
224   unformat_input_t *sub_input = va_arg (*args, unformat_input_t *);
225   u8 *s;
226   uword c;
227
228   while (1)
229     {
230       c = unformat_get_input (i);
231       switch (c)
232         {
233         case ' ':
234         case '\t':
235         case '\n':
236         case '\r':
237         case '\f':
238           break;
239
240         case '{':
241         default:
242           /* Put back paren. */
243           if (c != UNFORMAT_END_OF_INPUT)
244             unformat_put_input (i);
245
246           if (c == '{' && unformat (i, "%v", &s))
247             {
248               unformat_init_vector (sub_input, s);
249               return 1;
250             }
251           return 0;
252         }
253     }
254   return 0;
255 }
256
257 static vlib_cli_command_t *
258 get_sub_command (vlib_cli_main_t * cm, vlib_cli_command_t * parent, u32 si)
259 {
260   vlib_cli_sub_command_t *s = vec_elt_at_index (parent->sub_commands, si);
261   return vec_elt_at_index (cm->commands, s->index);
262 }
263
264 static uword
265 unformat_vlib_cli_sub_command (unformat_input_t * i, va_list * args)
266 {
267   vlib_main_t __clib_unused *vm = va_arg (*args, vlib_main_t *);
268   vlib_global_main_t *vgm = vlib_get_global_main ();
269   vlib_cli_command_t *c = va_arg (*args, vlib_cli_command_t *);
270   vlib_cli_command_t **result = va_arg (*args, vlib_cli_command_t **);
271   vlib_cli_main_t *cm = &vgm->cli_main;
272   uword *match_bitmap, is_unique, index;
273
274   match_bitmap = vlib_cli_sub_command_match (c, i);
275   is_unique = clib_bitmap_count_set_bits (match_bitmap) == 1;
276   index = ~0;
277   if (is_unique)
278     {
279       index = clib_bitmap_first_set (match_bitmap);
280       *result = get_sub_command (cm, c, index);
281     }
282   clib_bitmap_free (match_bitmap);
283
284   return is_unique;
285 }
286
287 static int
288 vlib_cli_cmp_strings (void *a1, void *a2)
289 {
290   u8 *c1 = *(u8 **) a1;
291   u8 *c2 = *(u8 **) a2;
292
293   return vec_cmp (c1, c2);
294 }
295
296 u8 **
297 vlib_cli_get_possible_completions (u8 * str)
298 {
299   vlib_cli_command_t *c;
300   vlib_cli_sub_command_t *sc;
301   vlib_global_main_t *vgm = vlib_get_global_main ();
302   vlib_cli_main_t *vcm = &vgm->cli_main;
303   uword *match_bitmap = 0;
304   uword index, is_unique, help_next_level;
305   u8 **result = 0;
306   unformat_input_t input;
307   unformat_init_vector (&input, vec_dup (str));
308   c = vec_elt_at_index (vcm->commands, 0);
309
310   /* remove trailing whitespace, except for one of them */
311   while (vec_len (input.buffer) >= 2 &&
312          isspace (input.buffer[vec_len (input.buffer) - 1]) &&
313          isspace (input.buffer[vec_len (input.buffer) - 2]))
314     {
315       vec_del1 (input.buffer, vec_len (input.buffer) - 1);
316     }
317
318   /* if input is empty, directly return list of root commands */
319   if (vec_len (input.buffer) == 0 ||
320       (vec_len (input.buffer) == 1 && isspace (input.buffer[0])))
321     {
322       vec_foreach (sc, c->sub_commands)
323       {
324         vec_add1 (result, (u8 *) sc->name);
325       }
326       goto done;
327     }
328
329   /* add a trailing '?' so that vlib_cli_sub_command_match can find
330    * all commands starting with the input string */
331   vec_add1 (input.buffer, '?');
332
333   while (1)
334     {
335       match_bitmap = vlib_cli_sub_command_match (c, &input);
336       /* no match: return no result */
337       if (match_bitmap == 0)
338         {
339           goto done;
340         }
341       is_unique = clib_bitmap_count_set_bits (match_bitmap) == 1;
342       /* unique match: try to step one subcommand level further */
343       if (is_unique)
344         {
345           /* stop if no more input */
346           if (input.index >= vec_len (input.buffer) - 1)
347             {
348               break;
349             }
350
351           index = clib_bitmap_first_set (match_bitmap);
352           c = get_sub_command (vcm, c, index);
353           clib_bitmap_free (match_bitmap);
354           continue;
355         }
356       /* multiple matches: stop here, return all matches */
357       break;
358     }
359
360   /* remove trailing '?' */
361   vec_del1 (input.buffer, vec_len (input.buffer) - 1);
362
363   /* if we have a space at the end of input, and a unique match,
364    * autocomplete the next level of subcommands */
365   help_next_level = (vec_len (str) == 0) || isspace (str[vec_len (str) - 1]);
366   /* *INDENT-OFF* */
367   clib_bitmap_foreach (index, match_bitmap) {
368     if (help_next_level && is_unique) {
369         c = get_sub_command (vcm, c, index);
370         vec_foreach (sc, c->sub_commands) {
371           vec_add1 (result, (u8*) sc->name);
372         }
373         goto done; /* break doesn't work in this macro-loop */
374     }
375     sc = &c->sub_commands[index];
376     vec_add1(result, (u8*) sc->name);
377   }
378   /* *INDENT-ON* */
379
380 done:
381   clib_bitmap_free (match_bitmap);
382   unformat_free (&input);
383
384   if (result)
385     vec_sort_with_function (result, vlib_cli_cmp_strings);
386   return result;
387 }
388
389 static u8 *
390 format_vlib_cli_command_help (u8 * s, va_list * args)
391 {
392   vlib_cli_command_t *c = va_arg (*args, vlib_cli_command_t *);
393   int is_long = va_arg (*args, int);
394   if (is_long && c->long_help)
395     s = format (s, "%s", c->long_help);
396   else if (c->short_help)
397     s = format (s, "%s", c->short_help);
398   else
399     s = format (s, "%v commands", c->path);
400   return s;
401 }
402
403 static u8 *
404 format_vlib_cli_path (u8 * s, va_list * args)
405 {
406   u8 *path = va_arg (*args, u8 *);
407
408   s = format (s, "%v", path);
409
410   return s;
411 }
412
413 static vlib_cli_command_t *
414 all_subs (vlib_cli_main_t * cm, vlib_cli_command_t * subs, u32 command_index)
415 {
416   vlib_cli_command_t *c = vec_elt_at_index (cm->commands, command_index);
417   vlib_cli_sub_command_t *sc;
418
419   if (c->function)
420     vec_add1 (subs, c[0]);
421
422   vec_foreach (sc, c->sub_commands) subs = all_subs (cm, subs, sc->index);
423
424   return subs;
425 }
426
427 static int
428 vlib_cli_cmp_rule (void *a1, void *a2)
429 {
430   vlib_cli_sub_rule_t *r1 = a1;
431   vlib_cli_sub_rule_t *r2 = a2;
432
433   return vec_cmp (r1->name, r2->name);
434 }
435
436 static int
437 vlib_cli_cmp_command (void *a1, void *a2)
438 {
439   vlib_cli_command_t *c1 = a1;
440   vlib_cli_command_t *c2 = a2;
441
442   return vec_cmp (c1->path, c2->path);
443 }
444
445 static clib_error_t *
446 vlib_cli_dispatch_sub_commands (vlib_main_t * vm,
447                                 vlib_cli_main_t * cm,
448                                 unformat_input_t * input,
449                                 uword parent_command_index)
450 {
451   vlib_global_main_t *vgm = vlib_get_global_main ();
452   vlib_cli_command_t *parent, *c;
453   clib_error_t *error = 0;
454   unformat_input_t sub_input;
455   u8 *string;
456   uword is_main_dispatch = cm == &vgm->cli_main;
457
458   parent = vec_elt_at_index (cm->commands, parent_command_index);
459   if (is_main_dispatch && unformat (input, "help"))
460     {
461       uword help_at_end_of_line, i;
462
463       help_at_end_of_line =
464         unformat_check_input (input) == UNFORMAT_END_OF_INPUT;
465       while (1)
466         {
467           c = parent;
468           if (unformat_user
469               (input, unformat_vlib_cli_sub_command, vm, c, &parent))
470             ;
471
472           else if (!(unformat_check_input (input) == UNFORMAT_END_OF_INPUT))
473             goto unknown;
474
475           else
476             break;
477         }
478
479       /* help SUB-COMMAND => long format help.
480          "help" at end of line: show all commands. */
481       if (!help_at_end_of_line)
482         vlib_cli_output (vm, "%U", format_vlib_cli_command_help, c,
483                          /* is_long */ 1);
484
485       else if (vec_len (c->sub_commands) == 0)
486         vlib_cli_output (vm, "%v: no sub-commands", c->path);
487
488       else
489         {
490           vlib_cli_sub_rule_t *sr, *subs = 0;
491           vlib_cli_sub_command_t *sc;
492
493           vec_foreach (sc, c->sub_commands)
494           {
495             vec_add2 (subs, sr, 1);
496             sr->name = sc->name;
497             sr->command_index = sc->index;
498             sr->rule_index = ~0;
499           }
500
501           vec_sort_with_function (subs, vlib_cli_cmp_rule);
502
503           for (i = 0; i < vec_len (subs); i++)
504             {
505               vlib_cli_command_t *d;
506
507               d = vec_elt_at_index (cm->commands, subs[i].command_index);
508               vlib_cli_output
509                 (vm, "  %-30v %U", subs[i].name,
510                  format_vlib_cli_command_help, d, /* is_long */ 0);
511             }
512
513           vec_free (subs);
514         }
515     }
516
517   else if (is_main_dispatch
518            && (unformat (input, "choices") || unformat (input, "?")))
519     {
520       vlib_cli_command_t *sub, *subs;
521
522       subs = all_subs (cm, 0, parent_command_index);
523       vec_sort_with_function (subs, vlib_cli_cmp_command);
524       vec_foreach (sub, subs)
525         vlib_cli_output (vm, "  %-40U %U",
526                          format_vlib_cli_path, sub->path,
527                          format_vlib_cli_command_help, sub, /* is_long */ 0);
528       vec_free (subs);
529     }
530
531   else if (unformat (input, "comment %v", &string))
532     {
533       vec_free (string);
534     }
535
536   else if (unformat (input, "vpplog %v", &string))
537     {
538       int i;
539       /*
540        * Delete leading whitespace, so "vpplog { this and that }"
541        * and "vpplog this" line up nicely.
542        */
543       for (i = 0; i < vec_len (string); i++)
544         if (string[i] != ' ')
545           break;
546       if (i > 0)
547         vec_delete (string, i, 0);
548
549       vlib_log_notice (cm->log, "CLI: %v", string);
550       vec_free (string);
551     }
552
553   else if (unformat (input, "uncomment %U",
554                      unformat_vlib_cli_sub_input, &sub_input))
555     {
556       error =
557         vlib_cli_dispatch_sub_commands (vm, cm, &sub_input,
558                                         parent_command_index);
559       unformat_free (&sub_input);
560     }
561   else if (unformat (input, "leak-check %U",
562                      unformat_vlib_cli_sub_input, &sub_input))
563     {
564       u8 *leak_report;
565       if (current_traced_heap)
566         {
567           void *oldheap;
568           oldheap = clib_mem_set_heap (current_traced_heap);
569           clib_mem_trace (0);
570           clib_mem_set_heap (oldheap);
571           current_traced_heap = 0;
572         }
573       clib_mem_trace (1);
574       error =
575         vlib_cli_dispatch_sub_commands (vm, cm, &sub_input,
576                                         parent_command_index);
577       unformat_free (&sub_input);
578
579       /* Otherwise, the clib_error_t shows up as a leak... */
580       if (error)
581         {
582           vlib_cli_output (vm, "%v", error->what);
583           clib_error_free (error);
584           error = 0;
585         }
586
587       (void) clib_mem_trace_enable_disable (0);
588       leak_report = format (0, "%U", format_clib_mem_heap, 0,
589                             1 /* verbose, i.e. print leaks */ );
590       clib_mem_trace (0);
591       vlib_cli_output (vm, "%v", leak_report);
592       vec_free (leak_report);
593     }
594
595   else
596     if (unformat_user (input, unformat_vlib_cli_sub_command, vm, parent, &c))
597     {
598       unformat_input_t *si;
599       uword has_sub_commands =
600         vec_len (c->sub_commands) + vec_len (c->sub_rules) > 0;
601
602       si = input;
603       if (unformat_user (input, unformat_vlib_cli_sub_input, &sub_input))
604         si = &sub_input;
605
606       if (has_sub_commands)
607         error = vlib_cli_dispatch_sub_commands (vm, cm, si, c - cm->commands);
608
609       if (has_sub_commands && !error)
610         /* Found valid sub-command. */ ;
611
612       else if (c->function)
613         {
614           clib_error_t *c_error;
615
616           /* Skip white space for benefit of called function. */
617           unformat_skip_white_space (si);
618
619           if (unformat (si, "?"))
620             {
621               vlib_cli_output (vm, "  %-40U %U", format_vlib_cli_path, c->path, format_vlib_cli_command_help, c,        /* is_long */
622                                0);
623             }
624           else
625             {
626               if (PREDICT_FALSE (vm->elog_trace_cli_commands))
627                 {
628                   /* *INDENT-OFF* */
629                   ELOG_TYPE_DECLARE (e) =
630                     {
631                       .format = "cli-cmd: %s",
632                       .format_args = "T4",
633                     };
634                   /* *INDENT-ON* */
635                   struct
636                   {
637                     u32 c;
638                   } *ed;
639                   ed = ELOG_DATA (vlib_get_elog_main (), e);
640                   ed->c = elog_string (vlib_get_elog_main (), "%v", c->path);
641                 }
642
643               if (!c->is_mp_safe)
644                 vlib_worker_thread_barrier_sync (vm);
645               if (PREDICT_FALSE (vec_len (cm->perf_counter_cbs) != 0))
646                 clib_call_callbacks (cm->perf_counter_cbs, cm,
647                                      c - cm->commands, 0 /* before */ );
648
649               c->hit_counter++;
650               c_error = c->function (vm, si, c);
651
652               if (PREDICT_FALSE (vec_len (cm->perf_counter_cbs) != 0))
653                 clib_call_callbacks (cm->perf_counter_cbs, cm,
654                                      c - cm->commands, 1 /* after */ );
655               if (!c->is_mp_safe)
656                 vlib_worker_thread_barrier_release (vm);
657
658               if (PREDICT_FALSE (vm->elog_trace_cli_commands))
659                 {
660                   /* *INDENT-OFF* */
661                   ELOG_TYPE_DECLARE (e) =
662                     {
663                       .format = "cli-cmd: %s %s",
664                       .format_args = "T4T4",
665                     };
666                   /* *INDENT-ON* */
667                   struct
668                   {
669                     u32 c, err;
670                   } *ed;
671                   ed = ELOG_DATA (vlib_get_elog_main (), e);
672                   ed->c = elog_string (vlib_get_elog_main (), "%v", c->path);
673                   if (c_error)
674                     {
675                       vec_add1 (c_error->what, 0);
676                       ed->err = elog_string (vlib_get_elog_main (),
677                                              (char *) c_error->what);
678                       vec_dec_len (c_error->what, 1);
679                     }
680                   else
681                     ed->err = elog_string (vlib_get_elog_main (), "OK");
682                 }
683
684               if (c_error)
685                 {
686                   error =
687                     clib_error_return (0, "%v: %v", c->path, c_error->what);
688                   clib_error_free (c_error);
689                   /* Free sub input. */
690                   if (si != input)
691                     unformat_free (si);
692
693                   return error;
694                 }
695             }
696
697           /* Free any previous error. */
698           clib_error_free (error);
699         }
700
701       else if (!error)
702         error = clib_error_return (0, "%v: no sub-commands", c->path);
703
704       /* Free sub input. */
705       if (si != input)
706         unformat_free (si);
707     }
708
709   else
710     goto unknown;
711
712   return error;
713
714 unknown:
715   if (parent->path)
716     return clib_error_return (0, "%v: unknown input `%U'", parent->path,
717                               format_unformat_error, input);
718   else
719     return clib_error_return (0, "unknown input `%U'", format_unformat_error,
720                               input);
721 }
722
723
724 void vlib_unix_error_report (vlib_main_t *, clib_error_t *)
725   __attribute__ ((weak));
726
727 void
728 vlib_unix_error_report (vlib_main_t * vm, clib_error_t * error)
729 {
730 }
731
732 /* Process CLI input. */
733 int
734 vlib_cli_input (vlib_main_t * vm,
735                 unformat_input_t * input,
736                 vlib_cli_output_function_t * function, uword function_arg)
737 {
738   vlib_global_main_t *vgm = vlib_get_global_main ();
739   vlib_process_t *cp = vlib_get_current_process (vm);
740   clib_error_t *error;
741   vlib_cli_output_function_t *save_function;
742   uword save_function_arg;
743   int rv = 0;
744
745   save_function = cp->output_function;
746   save_function_arg = cp->output_function_arg;
747
748   cp->output_function = function;
749   cp->output_function_arg = function_arg;
750
751   do
752     {
753       error = vlib_cli_dispatch_sub_commands (vm, &vgm->cli_main, input,
754                                               /* parent */ 0);
755     }
756   while (!error && !unformat (input, "%U", unformat_eof));
757
758   if (error)
759     {
760       vlib_cli_output (vm, "%v", error->what);
761       vlib_unix_error_report (vm, error);
762       /* clib_error_return is unfortunately often called with a '0'
763          return code */
764       rv = error->code != 0 ? error->code : -1;
765       clib_error_free (error);
766     }
767
768   cp->output_function = save_function;
769   cp->output_function_arg = save_function_arg;
770   return rv;
771 }
772
773 /* Output to current CLI connection. */
774 void
775 vlib_cli_output (vlib_main_t * vm, char *fmt, ...)
776 {
777   vlib_process_t *cp = vlib_get_current_process (vm);
778   va_list va;
779   u8 *s;
780
781   va_start (va, fmt);
782   s = va_format (0, fmt, &va);
783   va_end (va);
784
785   /* some format functions might return 0
786    * e.g. show int addr */
787   if (NULL == s)
788     return;
789
790   /* Terminate with \n if not present. */
791   if (vec_len (s) > 0 && s[vec_len (s) - 1] != '\n')
792     vec_add1 (s, '\n');
793
794   if ((!cp) || (!cp->output_function))
795     fformat (stdout, "%v", s);
796   else
797     cp->output_function (cp->output_function_arg, s, vec_len (s));
798
799   vec_free (s);
800 }
801
802 void *vl_msg_push_heap (void) __attribute__ ((weak));
803 void *
804 vl_msg_push_heap (void)
805 {
806   return 0;
807 }
808
809 void vl_msg_pop_heap (void *oldheap) __attribute__ ((weak));
810 void
811 vl_msg_pop_heap (void *oldheap)
812 {
813 }
814
815 static clib_error_t *
816 show_memory_usage (vlib_main_t * vm,
817                    unformat_input_t * input, vlib_cli_command_t * cmd)
818 {
819   clib_mem_main_t *mm = &clib_mem_main;
820   int verbose __attribute__ ((unused)) = 0;
821   int api_segment = 0, stats_segment = 0, main_heap = 0, numa_heaps = 0;
822   int map = 0;
823   clib_error_t *error;
824   u32 index = 0;
825   int i;
826   uword clib_mem_trace_enable_disable (uword enable);
827   uword was_enabled;
828
829
830   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
831     {
832       if (unformat (input, "verbose"))
833         verbose = 1;
834       else if (unformat (input, "api-segment"))
835         api_segment = 1;
836       else if (unformat (input, "stats-segment"))
837         stats_segment = 1;
838       else if (unformat (input, "main-heap"))
839         main_heap = 1;
840       else if (unformat (input, "numa-heaps"))
841         numa_heaps = 1;
842       else if (unformat (input, "map"))
843         map = 1;
844       else
845         {
846           error = clib_error_return (0, "unknown input `%U'",
847                                      format_unformat_error, input);
848           return error;
849         }
850     }
851
852   if ((api_segment + stats_segment + main_heap + numa_heaps + map) == 0)
853     return clib_error_return
854       (0, "Need one of api-segment, stats-segment, main-heap, numa-heaps "
855        "or map");
856
857   if (api_segment)
858     {
859       void *oldheap = vl_msg_push_heap ();
860       was_enabled = clib_mem_trace_enable_disable (0);
861       u8 *s_in_svm = format (0, "%U\n", format_clib_mem_heap, 0, 1);
862       vl_msg_pop_heap (oldheap);
863       u8 *s = vec_dup (s_in_svm);
864
865       oldheap = vl_msg_push_heap ();
866       vec_free (s_in_svm);
867       clib_mem_trace_enable_disable (was_enabled);
868       vl_msg_pop_heap (oldheap);
869       vlib_cli_output (vm, "API segment");
870       vlib_cli_output (vm, "%v", s);
871       vec_free (s);
872     }
873   if (stats_segment)
874     {
875       void *oldheap = vlib_stats_set_heap ();
876       was_enabled = clib_mem_trace_enable_disable (0);
877       u8 *s_in_svm = format (0, "%U\n", format_clib_mem_heap, 0, 1);
878       if (oldheap)
879         clib_mem_set_heap (oldheap);
880       u8 *s = vec_dup (s_in_svm);
881
882       oldheap = vlib_stats_set_heap ();
883       vec_free (s_in_svm);
884       if (oldheap)
885         {
886           clib_mem_trace_enable_disable (was_enabled);
887           clib_mem_set_heap (oldheap);
888         }
889       vlib_cli_output (vm, "Stats segment");
890       vlib_cli_output (vm, "%v", s);
891       vec_free (s);
892     }
893
894
895   {
896     if (main_heap)
897       {
898         /*
899          * Note: the foreach_vlib_main causes allocator traffic,
900          * so shut off tracing before we go there...
901          */
902         was_enabled = clib_mem_trace_enable_disable (0);
903
904         foreach_vlib_main ()
905           {
906             vlib_cli_output (vm, "%sThread %d %s\n", index ? "\n" : "", index,
907                              vlib_worker_threads[index].name);
908             vlib_cli_output (vm, "  %U\n", format_clib_mem_heap,
909                              mm->per_cpu_mheaps[index], verbose);
910             index++;
911           }
912
913         /* Restore the trace flag */
914         clib_mem_trace_enable_disable (was_enabled);
915       }
916     if (numa_heaps)
917       {
918         for (i = 0; i < ARRAY_LEN (mm->per_numa_mheaps); i++)
919           {
920             if (mm->per_numa_mheaps[i] == 0)
921               continue;
922             if (mm->per_numa_mheaps[i] == mm->per_cpu_mheaps[i])
923               {
924                 vlib_cli_output (vm, "Numa %d uses the main heap...", i);
925                 continue;
926               }
927             was_enabled = clib_mem_trace_enable_disable (0);
928
929             vlib_cli_output (vm, "Numa %d:", i);
930             vlib_cli_output (vm, "  %U\n", format_clib_mem_heap,
931                              mm->per_numa_mheaps[index], verbose);
932           }
933       }
934     if (map)
935       {
936         clib_mem_page_stats_t stats = { };
937         clib_mem_vm_map_hdr_t *hdr = 0;
938         u8 *s = 0;
939         int numa = -1;
940
941         s = format (s, "\n%-16s%7s%5s%7s%7s",
942                     "StartAddr", "size", "FD", "PageSz", "Pages");
943         while ((numa = vlib_mem_get_next_numa_node (numa)) != -1)
944           s = format (s, " Numa%u", numa);
945         s = format (s, " NotMap");
946         s = format (s, " Name");
947         vlib_cli_output (vm, "%v", s);
948         vec_reset_length (s);
949
950         while ((hdr = clib_mem_vm_get_next_map_hdr (hdr)))
951           {
952             clib_mem_get_page_stats ((void *) hdr->base_addr,
953                                      hdr->log2_page_sz, hdr->num_pages,
954                                      &stats);
955             s = format (s, "%016lx%7U",
956                         hdr->base_addr, format_memory_size,
957                         hdr->num_pages << hdr->log2_page_sz);
958
959             if (hdr->fd != -1)
960               s = format (s, "%5d", hdr->fd);
961             else
962               s = format (s, "%5s", " ");
963
964             s = format (s, "%7U%7lu",
965                         format_log2_page_size, hdr->log2_page_sz,
966                         hdr->num_pages);
967             while ((numa = vlib_mem_get_next_numa_node (numa)) != -1)
968               s = format (s, "%6lu", stats.per_numa[numa]);
969             s = format (s, "%7lu", stats.not_mapped);
970             s = format (s, " %s", hdr->name);
971             vlib_cli_output (vm, "%v", s);
972             vec_reset_length (s);
973           }
974         vec_free (s);
975       }
976   }
977   return 0;
978 }
979
980 /* *INDENT-OFF* */
981 VLIB_CLI_COMMAND (show_memory_usage_command, static) = {
982   .path = "show memory",
983   .short_help = "show memory [api-segment][stats-segment][verbose]\n"
984   "            [numa-heaps][map]",
985   .function = show_memory_usage,
986 };
987 /* *INDENT-ON* */
988
989 static clib_error_t *
990 show_cpu (vlib_main_t * vm, unformat_input_t * input,
991           vlib_cli_command_t * cmd)
992 {
993 #define _(a,b,c) vlib_cli_output (vm, "%-25s " b, a ":", c);
994   _("Model name", "%U", format_cpu_model_name);
995   _("Microarch model (family)", "%U", format_cpu_uarch);
996   _("Flags", "%U", format_cpu_flags);
997   _("Base frequency", "%.2f GHz",
998     ((f64) vm->clib_time.clocks_per_second) * 1e-9);
999 #undef _
1000   return 0;
1001 }
1002
1003 /*?
1004  * Displays various information about the CPU.
1005  *
1006  * @cliexpar
1007  * @cliexstart{show cpu}
1008  * Model name:               Intel(R) Xeon(R) CPU E5-2667 v4 @ 3.20GHz
1009  * Microarchitecture:        Broadwell (Broadwell-EP/EX)
1010  * Flags:                    sse3 ssse3 sse41 sse42 avx avx2 aes
1011  * Base Frequency:           3.20 GHz
1012  * @cliexend
1013 ?*/
1014 /* *INDENT-OFF* */
1015 VLIB_CLI_COMMAND (show_cpu_command, static) = {
1016   .path = "show cpu",
1017   .short_help = "Show cpu information",
1018   .function = show_cpu,
1019 };
1020 /* *INDENT-ON* */
1021
1022 static clib_error_t *
1023 enable_disable_memory_trace (vlib_main_t * vm,
1024                              unformat_input_t * input,
1025                              vlib_cli_command_t * cmd)
1026 {
1027   clib_mem_main_t *mm = &clib_mem_main;
1028   unformat_input_t _line_input, *line_input = &_line_input;
1029   int enable = 1;
1030   int api_segment = 0;
1031   int stats_segment = 0;
1032   int main_heap = 0;
1033   u32 numa_id = ~0;
1034   void *oldheap;
1035
1036   if (!unformat_user (input, unformat_line_input, line_input))
1037     return 0;
1038
1039   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1040     {
1041       if (unformat (line_input, "%U", unformat_vlib_enable_disable, &enable))
1042         ;
1043       else if (unformat (line_input, "api-segment"))
1044         api_segment = 1;
1045       else if (unformat (line_input, "stats-segment"))
1046         stats_segment = 1;
1047       else if (unformat (line_input, "main-heap"))
1048         main_heap = 1;
1049       else if (unformat (line_input, "numa-heap %d", &numa_id))
1050         ;
1051       else
1052         {
1053           unformat_free (line_input);
1054           return clib_error_return (0, "invalid input");
1055         }
1056     }
1057   unformat_free (line_input);
1058
1059   if ((api_segment + stats_segment + main_heap + (enable == 0)
1060        + (numa_id != ~0)) == 0)
1061     {
1062       return clib_error_return
1063         (0, "Need one of main-heap, stats-segment, api-segment,\n"
1064          "numa-heap <nn> or disable");
1065     }
1066
1067   /* Turn off current trace, if any */
1068   if (current_traced_heap)
1069     {
1070       void *oldheap;
1071       oldheap = clib_mem_set_heap (current_traced_heap);
1072       clib_mem_trace (0);
1073       clib_mem_set_heap (oldheap);
1074       current_traced_heap = 0;
1075     }
1076
1077   if (enable == 0)
1078     return 0;
1079
1080   /* API segment */
1081   if (api_segment)
1082     {
1083       oldheap = vl_msg_push_heap ();
1084       current_traced_heap = clib_mem_get_heap ();
1085       clib_mem_trace (1);
1086       vl_msg_pop_heap (oldheap);
1087
1088     }
1089
1090   /* Stats segment */
1091   if (stats_segment)
1092     {
1093       oldheap = vlib_stats_set_heap ();
1094       current_traced_heap = clib_mem_get_heap ();
1095       clib_mem_trace (stats_segment);
1096       /* We don't want to call vlib_stats_pop_heap... */
1097       if (oldheap)
1098         clib_mem_set_heap (oldheap);
1099     }
1100
1101   /* main_heap */
1102   if (main_heap)
1103     {
1104       current_traced_heap = clib_mem_get_heap ();
1105       clib_mem_trace (main_heap);
1106     }
1107
1108   if (numa_id != ~0)
1109     {
1110       if (numa_id >= ARRAY_LEN (mm->per_numa_mheaps))
1111         return clib_error_return (0, "Numa %d out of range", numa_id);
1112       if (mm->per_numa_mheaps[numa_id] == 0)
1113         return clib_error_return (0, "Numa %d heap not active", numa_id);
1114
1115       if (mm->per_numa_mheaps[numa_id] == clib_mem_get_heap ())
1116         return clib_error_return (0, "Numa %d uses the main heap...",
1117                                   numa_id);
1118       current_traced_heap = mm->per_numa_mheaps[numa_id];
1119       oldheap = clib_mem_set_heap (current_traced_heap);
1120       clib_mem_trace (1);
1121       clib_mem_set_heap (oldheap);
1122     }
1123
1124
1125   return 0;
1126 }
1127
1128 /* *INDENT-OFF* */
1129 VLIB_CLI_COMMAND (enable_disable_memory_trace_command, static) = {
1130   .path = "memory-trace",
1131   .short_help = "memory-trace on|off [api-segment][stats-segment][main-heap]\n"
1132   "                   [numa-heap <numa-id>]\n",
1133   .function = enable_disable_memory_trace,
1134 };
1135 /* *INDENT-ON* */
1136
1137 static clib_error_t *
1138 restart_cmd_fn (vlib_main_t * vm, unformat_input_t * input,
1139                 vlib_cli_command_t * cmd)
1140 {
1141   vlib_global_main_t *vgm = vlib_get_global_main ();
1142   clib_file_main_t *fm = &file_main;
1143   clib_file_t *f;
1144
1145   /* environ(7) does not indicate a header for this */
1146   extern char **environ;
1147
1148   /* Close all known open files */
1149   /* *INDENT-OFF* */
1150   pool_foreach (f, fm->file_pool)
1151      {
1152       if (f->file_descriptor > 2)
1153         close(f->file_descriptor);
1154     }
1155   /* *INDENT-ON* */
1156
1157   /* Exec ourself */
1158   execve (vgm->name, (char **) vgm->argv, environ);
1159
1160   return 0;
1161 }
1162
1163 /* *INDENT-OFF* */
1164 VLIB_CLI_COMMAND (restart_cmd,static) = {
1165     .path = "restart",
1166     .short_help = "restart process",
1167     .function = restart_cmd_fn,
1168 };
1169 /* *INDENT-ON* */
1170
1171 #ifdef TEST_CODE
1172 /*
1173  * A trivial test harness to verify the per-process output_function
1174  * is working correcty.
1175  */
1176
1177 static clib_error_t *
1178 sleep_ten_seconds (vlib_main_t * vm,
1179                    unformat_input_t * input, vlib_cli_command_t * cmd)
1180 {
1181   u16 i;
1182   u16 my_id = rand ();
1183
1184   vlib_cli_output (vm, "Starting 10 seconds sleep with id %u\n", my_id);
1185
1186   for (i = 0; i < 10; i++)
1187     {
1188       vlib_process_wait_for_event_or_clock (vm, 1.0);
1189       vlib_cli_output (vm, "Iteration number %u, my id: %u\n", i, my_id);
1190     }
1191   vlib_cli_output (vm, "Done with sleep with id %u\n", my_id);
1192   return 0;
1193 }
1194
1195 /* *INDENT-OFF* */
1196 VLIB_CLI_COMMAND (ping_command, static) = {
1197   .path = "test sleep",
1198   .function = sleep_ten_seconds,
1199   .short_help = "Sleep for 10 seconds",
1200 };
1201 /* *INDENT-ON* */
1202 #endif /* ifdef TEST_CODE */
1203
1204 static uword
1205 vlib_cli_normalize_path (char *input, char **result)
1206 {
1207   char *i = input;
1208   char *s = 0;
1209   uword l = 0;
1210   uword index_of_last_space = ~0;
1211
1212   while (*i != 0)
1213     {
1214       u8 c = *i++;
1215       /* Multiple white space -> single space. */
1216       switch (c)
1217         {
1218         case ' ':
1219         case '\t':
1220         case '\n':
1221         case '\r':
1222           if (l > 0 && s[l - 1] != ' ')
1223             {
1224               vec_add1 (s, ' ');
1225               l++;
1226             }
1227           break;
1228
1229         default:
1230           if (l > 0 && s[l - 1] == ' ')
1231             index_of_last_space = vec_len (s);
1232           vec_add1 (s, c);
1233           l++;
1234           break;
1235         }
1236     }
1237
1238   /* Remove any extra space at end. */
1239   if (l > 0 && s[l - 1] == ' ')
1240     vec_dec_len (s, 1);
1241
1242   *result = s;
1243   return index_of_last_space;
1244 }
1245
1246 always_inline uword
1247 parent_path_len (char *path)
1248 {
1249   word i;
1250   for (i = vec_len (path) - 1; i >= 0; i--)
1251     {
1252       if (path[i] == ' ')
1253         return i;
1254     }
1255   return ~0;
1256 }
1257
1258 static void
1259 add_sub_command (vlib_cli_main_t * cm, uword parent_index, uword child_index)
1260 {
1261   vlib_cli_command_t *p, *c;
1262   vlib_cli_sub_command_t *sub_c;
1263   u8 *sub_name;
1264   word i, l;
1265
1266   p = vec_elt_at_index (cm->commands, parent_index);
1267   c = vec_elt_at_index (cm->commands, child_index);
1268
1269   l = parent_path_len (c->path);
1270   if (l == ~0)
1271     sub_name = vec_dup ((u8 *) c->path);
1272   else
1273     {
1274       ASSERT (l + 1 < vec_len (c->path));
1275       sub_name = 0;
1276       vec_add (sub_name, c->path + l + 1, vec_len (c->path) - (l + 1));
1277     }
1278
1279   /* "Can't happen," check mainly to shut up coverity */
1280   ALWAYS_ASSERT (sub_name != 0);
1281
1282   if (sub_name[0] == '%')
1283     {
1284       uword *q;
1285       vlib_cli_sub_rule_t *sr;
1286
1287       /* Remove %. */
1288       vec_delete (sub_name, 1, 0);
1289
1290       if (!p->sub_rule_index_by_name)
1291         p->sub_rule_index_by_name = hash_create_vec ( /* initial length */ 32,
1292                                                      sizeof (sub_name[0]),
1293                                                      sizeof (uword));
1294       q = hash_get_mem (p->sub_rule_index_by_name, sub_name);
1295       if (q)
1296         {
1297           sr = vec_elt_at_index (p->sub_rules, q[0]);
1298           ASSERT (sr->command_index == child_index);
1299           return;
1300         }
1301
1302       hash_set_mem (p->sub_rule_index_by_name, sub_name,
1303                     vec_len (p->sub_rules));
1304       vec_add2 (p->sub_rules, sr, 1);
1305       sr->name = sub_name;
1306       sr->rule_index = sr - p->sub_rules;
1307       sr->command_index = child_index;
1308       return;
1309     }
1310
1311   if (!p->sub_command_index_by_name)
1312     p->sub_command_index_by_name = hash_create_vec ( /* initial length */ 32,
1313                                                     sizeof (c->path[0]),
1314                                                     sizeof (uword));
1315
1316   /* Check if sub-command has already been created. */
1317   if (hash_get_mem (p->sub_command_index_by_name, sub_name))
1318     {
1319       vec_free (sub_name);
1320       return;
1321     }
1322
1323   vec_add2 (p->sub_commands, sub_c, 1);
1324   sub_c->index = child_index;
1325   sub_c->name = sub_name;
1326   hash_set_mem (p->sub_command_index_by_name, sub_c->name,
1327                 sub_c - p->sub_commands);
1328
1329   vec_validate (p->sub_command_positions, vec_len (sub_c->name) - 1);
1330   for (i = 0; i < vec_len (sub_c->name); i++)
1331     {
1332       int n;
1333       vlib_cli_parse_position_t *pos;
1334
1335       pos = vec_elt_at_index (p->sub_command_positions, i);
1336
1337       if (!pos->bitmaps)
1338         pos->min_char = sub_c->name[i];
1339
1340       n = sub_c->name[i] - pos->min_char;
1341       if (n < 0)
1342         {
1343           pos->min_char = sub_c->name[i];
1344           vec_insert (pos->bitmaps, -n, 0);
1345           n = 0;
1346         }
1347
1348       vec_validate (pos->bitmaps, n);
1349       pos->bitmaps[n] =
1350         clib_bitmap_ori (pos->bitmaps[n], sub_c - p->sub_commands);
1351     }
1352 }
1353
1354 static void
1355 vlib_cli_make_parent (vlib_cli_main_t * cm, uword ci)
1356 {
1357   uword p_len, pi, *p;
1358   char *p_path;
1359   vlib_cli_command_t *c, *parent;
1360
1361   /* Root command (index 0) should have already been added. */
1362   ASSERT (vec_len (cm->commands) > 0);
1363
1364   c = vec_elt_at_index (cm->commands, ci);
1365   p_len = parent_path_len (c->path);
1366
1367   /* No space?  Parent is root command. */
1368   if (p_len == ~0)
1369     {
1370       add_sub_command (cm, 0, ci);
1371       return;
1372     }
1373
1374   p_path = 0;
1375   vec_add (p_path, c->path, p_len);
1376
1377   p = hash_get_mem (cm->command_index_by_path, p_path);
1378
1379   /* Parent exists? */
1380   if (!p)
1381     {
1382       /* Parent does not exist; create it. */
1383       vec_add2 (cm->commands, parent, 1);
1384       parent->path = p_path;
1385       hash_set_mem (cm->command_index_by_path, parent->path,
1386                     parent - cm->commands);
1387       pi = parent - cm->commands;
1388     }
1389   else
1390     {
1391       pi = p[0];
1392       vec_free (p_path);
1393     }
1394
1395   add_sub_command (cm, pi, ci);
1396
1397   /* Create parent's parent. */
1398   if (!p)
1399     vlib_cli_make_parent (cm, pi);
1400 }
1401
1402 always_inline uword
1403 vlib_cli_command_is_empty (vlib_cli_command_t * c)
1404 {
1405   return (c->long_help == 0 && c->short_help == 0 && c->function == 0);
1406 }
1407
1408 clib_error_t *
1409 vlib_cli_register (vlib_main_t * vm, vlib_cli_command_t * c)
1410 {
1411   vlib_global_main_t *vgm = vlib_get_global_main ();
1412   vlib_cli_main_t *cm = &vgm->cli_main;
1413   clib_error_t *error = 0;
1414   uword ci, *p;
1415   char *normalized_path;
1416
1417   if ((error = vlib_call_init_function (vm, vlib_cli_init)))
1418     return error;
1419
1420   (void) vlib_cli_normalize_path (c->path, &normalized_path);
1421
1422   if (!cm->command_index_by_path)
1423     cm->command_index_by_path = hash_create_vec ( /* initial length */ 32,
1424                                                  sizeof (c->path[0]),
1425                                                  sizeof (uword));
1426
1427   /* See if command already exists with given path. */
1428   p = hash_get_mem (cm->command_index_by_path, normalized_path);
1429   if (p)
1430     {
1431       vlib_cli_command_t *d;
1432
1433       ci = p[0];
1434       d = vec_elt_at_index (cm->commands, ci);
1435
1436       /* If existing command was created via vlib_cli_make_parent
1437          replaced it with callers data. */
1438       if (vlib_cli_command_is_empty (d))
1439         {
1440           vlib_cli_command_t save = d[0];
1441
1442           ASSERT (!vlib_cli_command_is_empty (c));
1443
1444           /* Copy callers fields. */
1445           d[0] = c[0];
1446
1447           /* Save internal fields. */
1448           d->path = save.path;
1449           d->sub_commands = save.sub_commands;
1450           d->sub_command_index_by_name = save.sub_command_index_by_name;
1451           d->sub_command_positions = save.sub_command_positions;
1452           d->sub_rules = save.sub_rules;
1453         }
1454       else
1455         error =
1456           clib_error_return (0, "duplicate command name with path %v",
1457                              normalized_path);
1458
1459       vec_free (normalized_path);
1460       if (error)
1461         return error;
1462     }
1463   else
1464     {
1465       /* Command does not exist: create it. */
1466
1467       /* Add root command (index 0). */
1468       if (vec_len (cm->commands) == 0)
1469         {
1470           /* Create command with index 0; path is empty string. */
1471           vec_resize (cm->commands, 1);
1472         }
1473
1474       ci = vec_len (cm->commands);
1475       hash_set_mem (cm->command_index_by_path, normalized_path, ci);
1476       vec_add1 (cm->commands, c[0]);
1477
1478       c = vec_elt_at_index (cm->commands, ci);
1479       c->path = normalized_path;
1480
1481       /* Don't inherit from registration. */
1482       c->sub_commands = 0;
1483       c->sub_command_index_by_name = 0;
1484       c->sub_command_positions = 0;
1485     }
1486
1487   vlib_cli_make_parent (cm, ci);
1488   return 0;
1489 }
1490
1491 #if 0
1492 /* $$$ turn back on again someday, maybe */
1493 clib_error_t *
1494 vlib_cli_register_parse_rule (vlib_main_t * vm, vlib_cli_parse_rule_t * r_reg)
1495 {
1496   vlib_cli_main_t *cm = &vm->cli_main;
1497   vlib_cli_parse_rule_t *r;
1498   clib_error_t *error = 0;
1499   u8 *r_name;
1500   uword *p;
1501
1502   if (!cm->parse_rule_index_by_name)
1503     cm->parse_rule_index_by_name = hash_create_vec ( /* initial length */ 32,
1504                                                     sizeof (r->name[0]),
1505                                                     sizeof (uword));
1506
1507   /* Make vector copy of name. */
1508   r_name = format (0, "%s", r_reg->name);
1509
1510   if ((p = hash_get_mem (cm->parse_rule_index_by_name, r_name)))
1511     {
1512       vec_free (r_name);
1513       return clib_error_return (0, "duplicate parse rule name `%s'",
1514                                 r_reg->name);
1515     }
1516
1517   vec_add2 (cm->parse_rules, r, 1);
1518   r[0] = r_reg[0];
1519   r->name = (char *) r_name;
1520   hash_set_mem (cm->parse_rule_index_by_name, r->name, r - cm->parse_rules);
1521
1522   return error;
1523 }
1524
1525 static clib_error_t *vlib_cli_register_parse_rules (vlib_main_t * vm,
1526                                                     vlib_cli_parse_rule_t *
1527                                                     lo,
1528                                                     vlib_cli_parse_rule_t *
1529                                                     hi)
1530   __attribute__ ((unused))
1531 {
1532   clib_error_t *error = 0;
1533   vlib_cli_parse_rule_t *r;
1534
1535   for (r = lo; r < hi; r = clib_elf_section_data_next (r, 0))
1536     {
1537       if (!r->name || strlen (r->name) == 0)
1538         {
1539           error = clib_error_return (0, "parse rule with no name");
1540           goto done;
1541         }
1542
1543       error = vlib_cli_register_parse_rule (vm, r);
1544       if (error)
1545         goto done;
1546     }
1547
1548 done:
1549   return error;
1550 }
1551 #endif
1552
1553 static clib_error_t *
1554 event_logger_trace_command_fn (vlib_main_t * vm,
1555                                unformat_input_t * input,
1556                                vlib_cli_command_t * cmd)
1557 {
1558   unformat_input_t _line_input, *line_input = &_line_input;
1559   int enable = 1;
1560   int api = 0, cli = 0, barrier = 0, dispatch = 0, circuit = 0;
1561   u32 circuit_node_index;
1562
1563   if (!unformat_user (input, unformat_line_input, line_input))
1564     goto print_status;
1565
1566   while (unformat_check_input (line_input) != UNFORMAT_END_OF_INPUT)
1567     {
1568       if (unformat (line_input, "api"))
1569         api = 1;
1570       else if (unformat (line_input, "dispatch"))
1571         dispatch = 1;
1572       else if (unformat (line_input, "circuit-node %U",
1573                          unformat_vlib_node, vm, &circuit_node_index))
1574         circuit = 1;
1575       else if (unformat (line_input, "cli"))
1576         cli = 1;
1577       else if (unformat (line_input, "barrier"))
1578         barrier = 1;
1579       else if (unformat (line_input, "disable"))
1580         enable = 0;
1581       else if (unformat (line_input, "enable"))
1582         enable = 1;
1583       else
1584         break;
1585     }
1586   unformat_free (line_input);
1587
1588   vl_api_set_elog_trace_api_messages
1589     (api ? enable : vl_api_get_elog_trace_api_messages ());
1590   vm->elog_trace_cli_commands = cli ? enable : vm->elog_trace_cli_commands;
1591   vm->elog_trace_graph_dispatch = dispatch ?
1592     enable : vm->elog_trace_graph_dispatch;
1593   vm->elog_trace_graph_circuit = circuit ?
1594     enable : vm->elog_trace_graph_circuit;
1595   vlib_worker_threads->barrier_elog_enabled =
1596     barrier ? enable : vlib_worker_threads->barrier_elog_enabled;
1597   vm->elog_trace_graph_circuit_node_index = circuit_node_index;
1598
1599   /*
1600    * Set up start-of-buffer logic-analyzer trigger
1601    * for main loop event logs, which are fairly heavyweight.
1602    * See src/vlib/main/vlib_elog_main_loop_event(...), which
1603    * will fully disable the scheme when the elog buffer fills.
1604    */
1605   if (dispatch || circuit)
1606     {
1607       elog_main_t *em = &vlib_global_main.elog_main;
1608
1609       em->n_total_events_disable_limit =
1610         em->n_total_events + vec_len (em->event_ring);
1611     }
1612
1613
1614 print_status:
1615   vlib_cli_output (vm, "Current status:");
1616
1617   vlib_cli_output
1618     (vm, "    Event log API message trace: %s\n    CLI command trace: %s",
1619      vl_api_get_elog_trace_api_messages ()? "on" : "off",
1620      vm->elog_trace_cli_commands ? "on" : "off");
1621   vlib_cli_output
1622     (vm, "    Barrier sync trace: %s",
1623      vlib_worker_threads->barrier_elog_enabled ? "on" : "off");
1624   vlib_cli_output
1625     (vm, "    Graph Dispatch: %s",
1626      vm->elog_trace_graph_dispatch ? "on" : "off");
1627   vlib_cli_output
1628     (vm, "    Graph Circuit: %s",
1629      vm->elog_trace_graph_circuit ? "on" : "off");
1630   if (vm->elog_trace_graph_circuit)
1631     vlib_cli_output
1632       (vm, "                   node %U",
1633        format_vlib_node_name, vm, vm->elog_trace_graph_circuit_node_index);
1634
1635   return 0;
1636 }
1637
1638 /*?
1639  * Control event logging of api, cli, and thread barrier events
1640  * With no arguments, displays the current trace status.
1641  * Name the event groups you wish to trace or stop tracing.
1642  *
1643  * @cliexpar
1644  * @clistart
1645  * event-logger trace api cli barrier
1646  * event-logger trace api cli barrier disable
1647  * event-logger trace dispatch
1648  * event-logger trace circuit-node ethernet-input
1649  * @cliend
1650  * @cliexcmd{event-logger trace [api][cli][barrier][disable]}
1651 ?*/
1652 /* *INDENT-OFF* */
1653 VLIB_CLI_COMMAND (event_logger_trace_command, static) =
1654 {
1655   .path = "event-logger trace",
1656   .short_help = "event-logger trace [api][cli][barrier][dispatch]\n"
1657   "[circuit-node <name> e.g. ethernet-input][disable]",
1658   .function = event_logger_trace_command_fn,
1659 };
1660 /* *INDENT-ON* */
1661
1662 static clib_error_t *
1663 suspend_command_fn (vlib_main_t * vm,
1664                     unformat_input_t * input, vlib_cli_command_t * cmd)
1665 {
1666   vlib_process_suspend (vm, 30e-3);
1667   return 0;
1668 }
1669
1670 /* *INDENT-OFF* */
1671 VLIB_CLI_COMMAND (suspend_command, static) =
1672 {
1673   .path = "suspend",
1674   .short_help = "suspend debug CLI for 30ms",
1675   .function = suspend_command_fn,
1676   .is_mp_safe = 1,
1677 };
1678 /* *INDENT-ON* */
1679
1680
1681 static int
1682 sort_cmds_by_path (void *a1, void *a2)
1683 {
1684   u32 *index1 = a1;
1685   u32 *index2 = a2;
1686   vlib_global_main_t *vgm = vlib_get_global_main ();
1687   vlib_cli_main_t *cm = &vgm->cli_main;
1688   vlib_cli_command_t *c1, *c2;
1689   int i, lmin;
1690
1691   c1 = vec_elt_at_index (cm->commands, *index1);
1692   c2 = vec_elt_at_index (cm->commands, *index2);
1693
1694   lmin = vec_len (c1->path);
1695   lmin = (vec_len (c2->path) >= lmin) ? lmin : vec_len (c2->path);
1696
1697   for (i = 0; i < lmin; i++)
1698     {
1699       if (c1->path[i] < c2->path[i])
1700         return -1;
1701       else if (c1->path[i] > c2->path[i])
1702         return 1;
1703     }
1704
1705   return 0;
1706 }
1707
1708 typedef struct
1709 {
1710   vlib_cli_main_t *cm;
1711   u32 parent_command_index;
1712   int show_mp_safe;
1713   int show_not_mp_safe;
1714   int show_hit;
1715   int clear_hit;
1716 } vlib_cli_walk_args_t;
1717
1718 static void
1719 cli_recursive_walk (vlib_cli_walk_args_t * aa)
1720 {
1721   vlib_cli_command_t *parent;
1722   vlib_cli_sub_command_t *sub;
1723   vlib_cli_walk_args_t _a, *a = &_a;
1724   vlib_cli_main_t *cm;
1725   int i;
1726
1727   /* Copy args into this stack frame */
1728   *a = *aa;
1729   cm = a->cm;
1730
1731   parent = vec_elt_at_index (cm->commands, a->parent_command_index);
1732
1733   if (parent->function)
1734     {
1735       if (((a->show_mp_safe && parent->is_mp_safe)
1736            || (a->show_not_mp_safe && !parent->is_mp_safe))
1737           && (a->show_hit == 0 || parent->hit_counter))
1738         {
1739           vec_add1 (cm->sort_vector, a->parent_command_index);
1740         }
1741
1742       if (a->clear_hit)
1743         parent->hit_counter = 0;
1744     }
1745
1746   for (i = 0; i < vec_len (parent->sub_commands); i++)
1747     {
1748       sub = vec_elt_at_index (parent->sub_commands, i);
1749       a->parent_command_index = sub->index;
1750       cli_recursive_walk (a);
1751     }
1752 }
1753
1754 static u8 *
1755 format_mp_safe (u8 * s, va_list * args)
1756 {
1757   vlib_cli_main_t *cm = va_arg (*args, vlib_cli_main_t *);
1758   int show_mp_safe = va_arg (*args, int);
1759   int show_not_mp_safe = va_arg (*args, int);
1760   int show_hit = va_arg (*args, int);
1761   int clear_hit = va_arg (*args, int);
1762   vlib_cli_command_t *c;
1763   vlib_cli_walk_args_t _a, *a = &_a;
1764   int i;
1765   char *format_string = "\n%v";
1766
1767   if (show_hit)
1768     format_string = "\n%v: %u";
1769
1770   vec_reset_length (cm->sort_vector);
1771
1772   a->cm = cm;
1773   a->parent_command_index = 0;
1774   a->show_mp_safe = show_mp_safe;
1775   a->show_not_mp_safe = show_not_mp_safe;
1776   a->show_hit = show_hit;
1777   a->clear_hit = clear_hit;
1778
1779   cli_recursive_walk (a);
1780
1781   vec_sort_with_function (cm->sort_vector, sort_cmds_by_path);
1782
1783   for (i = 0; i < vec_len (cm->sort_vector); i++)
1784     {
1785       c = vec_elt_at_index (cm->commands, cm->sort_vector[i]);
1786       s = format (s, format_string, c->path, c->hit_counter);
1787     }
1788
1789   return s;
1790 }
1791
1792
1793 static clib_error_t *
1794 show_cli_command_fn (vlib_main_t * vm,
1795                      unformat_input_t * input, vlib_cli_command_t * cmd)
1796 {
1797   vlib_global_main_t *vgm = vlib_get_global_main ();
1798   int show_mp_safe = 0;
1799   int show_not_mp_safe = 0;
1800   int show_hit = 0;
1801   int clear_hit = 0;
1802
1803   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1804     {
1805       if (unformat (input, "mp-safe"))
1806         show_mp_safe = 1;
1807       if (unformat (input, "not-mp-safe"))
1808         show_not_mp_safe = 1;
1809       else if (unformat (input, "hit"))
1810         show_hit = 1;
1811       else if (unformat (input, "clear-hit"))
1812         clear_hit = 1;
1813       else
1814         break;
1815     }
1816
1817   /* default set: all cli commands */
1818   if (clear_hit == 0 && (show_mp_safe + show_not_mp_safe) == 0)
1819     show_mp_safe = show_not_mp_safe = 1;
1820
1821   vlib_cli_output (vm, "%U", format_mp_safe, &vgm->cli_main, show_mp_safe,
1822                    show_not_mp_safe, show_hit, clear_hit);
1823   if (clear_hit)
1824     vlib_cli_output (vm, "hit counters cleared...");
1825
1826   return 0;
1827 }
1828
1829 /*?
1830  * Displays debug cli command information
1831  *
1832  * @cliexpar
1833  * @cliexstart{show cli [mp-safe][not-mp-safe][hit][clear-hit]}
1834  *
1835  * "show cli" displays the entire debug cli:
1836  *
1837  * abf attach
1838  * abf policy
1839  * adjacency counters
1840  * api trace
1841  * app ns
1842  * bfd key del
1843  * ... and so on ...
1844  *
1845  * "show cli mp-safe" displays mp-safe debug CLI commands:
1846  *
1847  * abf policy
1848  * binary-api
1849  * create vhost-user
1850  * exec
1851  * ip container
1852  * ip mroute
1853  * ip probe-neighbor
1854  * ip route
1855  * ip scan-neighbor
1856  * ip table
1857  * ip6 table
1858  *
1859  * "show cli not-mp-safe" displays debug CLI commands
1860  * which cause worker thread barrier synchronization
1861  *
1862  * "show cli hit" displays commands which have been executed. Qualify
1863  * as desired with "mp-safe" or "not-mp-safe".
1864  *
1865  * "show cli clear-hit" clears the per-command hit counters.
1866  * @cliexend
1867 ?*/
1868
1869 /* *INDENT-OFF* */
1870 VLIB_CLI_COMMAND (show_cli_command, static) =
1871 {
1872   .path = "show cli",
1873   .short_help = "show cli [mp-safe][not-mp-safe][hit][clear-hit]",
1874   .function = show_cli_command_fn,
1875   .is_mp_safe = 1,
1876 };
1877 /* *INDENT-ON* */
1878
1879 static clib_error_t *
1880 vlib_cli_init (vlib_main_t * vm)
1881 {
1882   vlib_global_main_t *vgm = vlib_get_global_main ();
1883   vlib_cli_main_t *cm = &vgm->cli_main;
1884   clib_error_t *error = 0;
1885   vlib_cli_command_t *cmd;
1886
1887   cmd = cm->cli_command_registrations;
1888
1889   while (cmd)
1890     {
1891       error = vlib_cli_register (vm, cmd);
1892       if (error)
1893         return error;
1894       cmd = cmd->next_cli_command;
1895     }
1896
1897   cm->log = vlib_log_register_class_rate_limit (
1898     "cli", "log", 0x7FFFFFFF /* aka no rate limit */);
1899   return error;
1900 }
1901
1902 VLIB_INIT_FUNCTION (vlib_cli_init);
1903
1904 /*
1905  * fd.io coding-style-patch-verification: ON
1906  *
1907  * Local Variables:
1908  * eval: (c-set-style "gnu")
1909  * End:
1910  */