source: mainline/kernel/generic/src/console/kconsole.c@ 3266412

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 3266412 was 3266412, checked in by Aurelio Colosimo <aurelio@…>, 9 years ago

kconsole tab completion: implement args completion for 'describe' and 'symaddr'

  • Property mode set to 100644
File size: 18.5 KB
Line 
1/*
2 * Copyright (c) 2005 Jakub Jermar
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup genericconsole
30 * @{
31 */
32
33/**
34 * @file kconsole.c
35 * @brief Kernel console.
36 *
37 * This file contains kernel thread managing the kernel console.
38 *
39 */
40
41#include <console/kconsole.h>
42#include <console/console.h>
43#include <console/chardev.h>
44#include <console/cmd.h>
45#include <console/prompt.h>
46#include <print.h>
47#include <panic.h>
48#include <typedefs.h>
49#include <adt/list.h>
50#include <arch.h>
51#include <macros.h>
52#include <debug.h>
53#include <func.h>
54#include <str.h>
55#include <sysinfo/sysinfo.h>
56#include <ddi/device.h>
57#include <symtab.h>
58#include <errno.h>
59#include <putchar.h>
60#include <str.h>
61#include <mm/slab.h>
62
63/** Simple kernel console.
64 *
65 * The console is realized by kernel thread kconsole.
66 * It doesn't understand any useful command on its own,
67 * but makes it possible for other kernel subsystems to
68 * register their own commands.
69 */
70
71/** Locking.
72 *
73 * There is a list of cmd_info_t structures. This list
74 * is protected by cmd_lock spinlock. Note that specially
75 * the link elements of cmd_info_t are protected by
76 * this lock.
77 *
78 * Each cmd_info_t also has its own lock, which protects
79 * all elements thereof except the link element.
80 *
81 * cmd_lock must be acquired before any cmd_info lock.
82 * When locking two cmd info structures, structure with
83 * lower address must be locked first.
84 */
85
86SPINLOCK_INITIALIZE(cmd_lock); /**< Lock protecting command list. */
87LIST_INITIALIZE(cmd_list); /**< Command list. */
88
89static wchar_t history[KCONSOLE_HISTORY][MAX_CMDLINE] = {};
90static size_t history_pos = 0;
91
92/** Initialize kconsole data structures
93 *
94 * This is the most basic initialization, almost no
95 * other kernel subsystem is ready yet.
96 *
97 */
98void kconsole_init(void)
99{
100 unsigned int i;
101
102 cmd_init();
103 for (i = 0; i < KCONSOLE_HISTORY; i++)
104 history[i][0] = 0;
105}
106
107/** Register kconsole command.
108 *
109 * @param cmd Structure describing the command.
110 *
111 * @return False on failure, true on success.
112 *
113 */
114bool cmd_register(cmd_info_t *cmd)
115{
116 spinlock_lock(&cmd_lock);
117
118 /*
119 * Make sure the command is not already listed.
120 */
121 list_foreach(cmd_list, link, cmd_info_t, hlp) {
122 if (hlp == cmd) {
123 /* The command is already there. */
124 spinlock_unlock(&cmd_lock);
125 return false;
126 }
127
128 /* Avoid deadlock. */
129 if (hlp < cmd) {
130 spinlock_lock(&hlp->lock);
131 spinlock_lock(&cmd->lock);
132 } else {
133 spinlock_lock(&cmd->lock);
134 spinlock_lock(&hlp->lock);
135 }
136
137 if (str_cmp(hlp->name, cmd->name) == 0) {
138 /* The command is already there. */
139 spinlock_unlock(&hlp->lock);
140 spinlock_unlock(&cmd->lock);
141 spinlock_unlock(&cmd_lock);
142 return false;
143 }
144
145 spinlock_unlock(&hlp->lock);
146 spinlock_unlock(&cmd->lock);
147 }
148
149 /*
150 * Now the command can be added.
151 */
152 list_append(&cmd->link, &cmd_list);
153
154 spinlock_unlock(&cmd_lock);
155 return true;
156}
157
158/** Print count times a character */
159NO_TRACE static void print_cc(wchar_t ch, size_t count)
160{
161 size_t i;
162 for (i = 0; i < count; i++)
163 putchar(ch);
164}
165
166/** Try to find a command beginning with prefix */
167const char *cmdtab_enum(const char *name, const char **h, void **ctx)
168{
169 link_t **startpos = (link_t**)ctx;
170 size_t namelen = str_length(name);
171
172 spinlock_lock(&cmd_lock);
173
174 if (*startpos == NULL)
175 *startpos = cmd_list.head.next;
176
177 for (; *startpos != &cmd_list.head; *startpos = (*startpos)->next) {
178 cmd_info_t *hlp = list_get_instance(*startpos, cmd_info_t, link);
179
180 const char *curname = hlp->name;
181 if (str_length(curname) < namelen)
182 continue;
183
184 if (str_lcmp(curname, name, namelen) == 0) {
185 *startpos = (*startpos)->next;
186 if (h) {
187 *h = hlp->description;
188 }
189 spinlock_unlock(&cmd_lock);
190 return (curname + str_lsize(curname, namelen));
191 }
192 }
193
194 spinlock_unlock(&cmd_lock);
195 return NULL;
196}
197
198/** Command completion of the commands
199 *
200 * @param name String to match, changed to hint on exit
201 * @param size Input buffer size
202 *
203 * @return Number of found matches
204 *
205 */
206NO_TRACE static int cmdtab_compl(char *input, size_t size, indev_t *indev,
207 hints_enum_func_t hints_enum)
208{
209 const char *name = input;
210
211 size_t found = 0;
212
213 /*
214 * Maximum Match Length: Length of longest matching common
215 * substring in case more than one match is found.
216 */
217 size_t max_match_len = size;
218 size_t max_match_len_tmp = size;
219 void *pos = NULL;
220 const char *hint;
221 const char *help;
222 char *output = malloc(MAX_CMDLINE, 0);
223 size_t hints_to_show = MAX_TAB_HINTS - 1;
224 size_t total_hints_shown = 0;
225 bool continue_showing_hints = true;
226
227 output[0] = 0;
228
229 while ((hint = hints_enum(name, NULL, &pos))) {
230 if ((found == 0) || (str_length(output) > str_length(hint)))
231 str_cpy(output, MAX_CMDLINE, hint);
232
233 found++;
234 }
235
236 /*
237 * If the number of possible completions is more than MAX_TAB_HINTS,
238 * ask the user whether to display them or not.
239 */
240 if (found > MAX_TAB_HINTS) {
241 printf("\n");
242 continue_showing_hints =
243 console_prompt_display_all_hints(indev, found);
244 }
245
246 if ((found > 1) && (str_length(output) != 0)) {
247 printf("\n");
248 pos = NULL;
249 while ((hint = hints_enum(name, &help, &pos))) {
250
251 if (continue_showing_hints) {
252
253 if (help)
254 printf("%s%s (%s)\n", name, hint, help);
255 else
256 printf("%s%s\n", name, hint);
257
258 --hints_to_show;
259 ++total_hints_shown;
260
261 if ((hints_to_show == 0) && (total_hints_shown != found)) {
262 /* Ask user to continue */
263 continue_showing_hints =
264 console_prompt_more_hints(indev, &hints_to_show);
265 }
266 }
267
268 for (max_match_len_tmp = 0;
269 (output[max_match_len_tmp] ==
270 hint[max_match_len_tmp]) &&
271 (max_match_len_tmp < max_match_len); ++max_match_len_tmp);
272
273 max_match_len = max_match_len_tmp;
274 }
275
276 /* Keep only the characters common in all completions */
277 output[max_match_len] = 0;
278 }
279
280 if (found > 0)
281 str_cpy(input, size, output);
282
283 free(output);
284 return found;
285}
286
287NO_TRACE static cmd_info_t *parse_cmd(const wchar_t *cmdline)
288{
289 size_t start = 0;
290 size_t end;
291 char *tmp;
292
293 while (isspace(cmdline[start]))
294 start++;
295 end = start + 1;
296 while (!isspace(cmdline[end]))
297 end++;
298
299 tmp = malloc(STR_BOUNDS(end - start + 1), 0);
300
301 wstr_to_str(tmp, end - start + 1, &cmdline[start]);
302
303 spinlock_lock(&cmd_lock);
304
305 list_foreach(cmd_list, link, cmd_info_t, hlp) {
306 spinlock_lock(&hlp->lock);
307
308 if (str_cmp(hlp->name, tmp) == 0) {
309 spinlock_unlock(&hlp->lock);
310 spinlock_unlock(&cmd_lock);
311 free(tmp);
312 return hlp;
313 }
314
315 spinlock_unlock(&hlp->lock);
316 }
317
318 free(tmp);
319 spinlock_unlock(&cmd_lock);
320
321 return NULL;
322}
323
324NO_TRACE static wchar_t *clever_readline(const char *prompt, indev_t *indev)
325{
326 printf("%s> ", prompt);
327
328 size_t position = 0;
329 wchar_t *current = history[history_pos];
330 current[0] = 0;
331 char *tmp = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
332
333 while (true) {
334 wchar_t ch = indev_pop_character(indev);
335
336 if (ch == '\n') {
337 /* Enter */
338 putchar(ch);
339 break;
340 }
341
342 if (ch == '\b') {
343 /* Backspace */
344 if (position == 0)
345 continue;
346
347 if (wstr_remove(current, position - 1)) {
348 position--;
349 putchar('\b');
350 printf("%ls ", current + position);
351 print_cc('\b', wstr_length(current) - position + 1);
352 continue;
353 }
354 }
355
356 if (ch == '\t') {
357 /* Tab completion */
358
359 /* Move to the end of the word */
360 for (; (current[position] != 0) && (!isspace(current[position]));
361 position++)
362 putchar(current[position]);
363
364 if (position == 0)
365 continue;
366
367 /*
368 * Find the beginning of the word
369 * and copy it to tmp
370 */
371 size_t beg;
372 for (beg = position - 1; (beg > 0) && (!isspace(current[beg]));
373 beg--);
374
375 if (isspace(current[beg]))
376 beg++;
377
378 wstr_to_str(tmp, position - beg + 1, current + beg);
379
380 int found;
381 if (beg == 0) {
382 /* Command completion */
383 found = cmdtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev,
384 cmdtab_enum);
385 } else {
386 /* Arguments completion */
387 cmd_info_t *cmd = parse_cmd(current);
388 if (!cmd || !cmd->hints_enum)
389 continue;
390 found = cmdtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev,
391 cmd->hints_enum);
392 }
393
394 if (found == 0)
395 continue;
396
397 /*
398 * We have hints, possibly many. In case of more than one hint,
399 * tmp will contain the common prefix.
400 */
401 size_t off = 0;
402 size_t i = 0;
403 while ((ch = str_decode(tmp, &off, STR_NO_LIMIT)) != 0) {
404 if (!wstr_linsert(current, ch, position + i, MAX_CMDLINE))
405 break;
406
407 i++;
408 }
409
410 if (found > 1) {
411 /* No unique hint, list was printed */
412 printf("%s> ", prompt);
413 printf("%ls", current);
414 position += str_length(tmp);
415 print_cc('\b', wstr_length(current) - position);
416 continue;
417 }
418
419 /* We have a hint */
420
421 printf("%ls", current + position);
422 position += str_length(tmp);
423 print_cc('\b', wstr_length(current) - position);
424
425 if (position == wstr_length(current)) {
426 /* Insert a space after the last completed argument */
427 if (wstr_linsert(current, ' ', position, MAX_CMDLINE)) {
428 printf("%ls", current + position);
429 position++;
430 }
431 }
432 continue;
433 }
434
435 if (ch == U_LEFT_ARROW) {
436 /* Left */
437 if (position > 0) {
438 putchar('\b');
439 position--;
440 }
441 continue;
442 }
443
444 if (ch == U_RIGHT_ARROW) {
445 /* Right */
446 if (position < wstr_length(current)) {
447 putchar(current[position]);
448 position++;
449 }
450 continue;
451 }
452
453 if ((ch == U_UP_ARROW) || (ch == U_DOWN_ARROW)) {
454 /* Up, down */
455 print_cc('\b', position);
456 print_cc(' ', wstr_length(current));
457 print_cc('\b', wstr_length(current));
458
459 if (ch == U_UP_ARROW) {
460 /* Up */
461 if (history_pos == 0)
462 history_pos = KCONSOLE_HISTORY - 1;
463 else
464 history_pos--;
465 } else {
466 /* Down */
467 history_pos++;
468 history_pos = history_pos % KCONSOLE_HISTORY;
469 }
470 current = history[history_pos];
471 printf("%ls", current);
472 position = wstr_length(current);
473 continue;
474 }
475
476 if (ch == U_HOME_ARROW) {
477 /* Home */
478 print_cc('\b', position);
479 position = 0;
480 continue;
481 }
482
483 if (ch == U_END_ARROW) {
484 /* End */
485 printf("%ls", current + position);
486 position = wstr_length(current);
487 continue;
488 }
489
490 if (ch == U_DELETE) {
491 /* Delete */
492 if (position == wstr_length(current))
493 continue;
494
495 if (wstr_remove(current, position)) {
496 printf("%ls ", current + position);
497 print_cc('\b', wstr_length(current) - position + 1);
498 }
499 continue;
500 }
501
502 if (wstr_linsert(current, ch, position, MAX_CMDLINE)) {
503 printf("%ls", current + position);
504 position++;
505 print_cc('\b', wstr_length(current) - position);
506 }
507 }
508
509 if (wstr_length(current) > 0) {
510 history_pos++;
511 history_pos = history_pos % KCONSOLE_HISTORY;
512 }
513
514 free(tmp);
515 return current;
516}
517
518bool kconsole_check_poll(void)
519{
520 return check_poll(stdin);
521}
522
523NO_TRACE static bool parse_int_arg(const char *text, size_t len,
524 sysarg_t *result)
525{
526 bool isaddr = false;
527 bool isptr = false;
528
529 /* If we get a name, try to find it in symbol table */
530 if (text[0] == '&') {
531 isaddr = true;
532 text++;
533 len--;
534 } else if (text[0] == '*') {
535 isptr = true;
536 text++;
537 len--;
538 }
539
540 if ((text[0] < '0') || (text[0] > '9')) {
541 char symname[MAX_SYMBOL_NAME];
542 str_ncpy(symname, MAX_SYMBOL_NAME, text, len + 1);
543
544 uintptr_t symaddr;
545 int rc = symtab_addr_lookup(symname, &symaddr);
546 switch (rc) {
547 case ENOENT:
548 printf("Symbol %s not found.\n", symname);
549 return false;
550 case EOVERFLOW:
551 printf("Duplicate symbol %s.\n", symname);
552 symtab_print_search(symname);
553 return false;
554 case ENOTSUP:
555 printf("No symbol information available.\n");
556 return false;
557 case EOK:
558 if (isaddr)
559 *result = (sysarg_t) symaddr;
560 else if (isptr)
561 *result = **((sysarg_t **) symaddr);
562 else
563 *result = *((sysarg_t *) symaddr);
564 break;
565 default:
566 printf("Unknown error.\n");
567 return false;
568 }
569 } else {
570 /* It's a number - convert it */
571 uint64_t value;
572 char *end;
573 int rc = str_uint64_t(text, &end, 0, false, &value);
574 if (end != text + len)
575 rc = EINVAL;
576 switch (rc) {
577 case EINVAL:
578 printf("Invalid number '%s'.\n", text);
579 return false;
580 case EOVERFLOW:
581 printf("Integer overflow in '%s'.\n", text);
582 return false;
583 case EOK:
584 *result = (sysarg_t) value;
585 if (isptr)
586 *result = *((sysarg_t *) *result);
587 break;
588 default:
589 printf("Unknown error parsing '%s'.\n", text);
590 return false;
591 }
592 }
593
594 return true;
595}
596
597/** Parse argument.
598 *
599 * Find start and end positions of command line argument.
600 *
601 * @param cmdline Command line as read from the input device.
602 * @param size Size (in bytes) of the string.
603 * @param start On entry, 'start' contains pointer to the offset
604 * of the first unprocessed character of cmdline.
605 * On successful exit, it marks beginning of the next argument.
606 * @param end Undefined on entry. On exit, 'end' is the offset of the first
607 * character behind the next argument.
608 *
609 * @return False on failure, true on success.
610 *
611 */
612NO_TRACE static bool parse_argument(const char *cmdline, size_t size,
613 size_t *start, size_t *end)
614{
615 ASSERT(start != NULL);
616 ASSERT(end != NULL);
617
618 bool found_start = false;
619 size_t offset = *start;
620 size_t prev = *start;
621 wchar_t ch;
622
623 while ((ch = str_decode(cmdline, &offset, size)) != 0) {
624 if (!found_start) {
625 if (!isspace(ch)) {
626 *start = prev;
627 found_start = true;
628 }
629 } else {
630 if (isspace(ch))
631 break;
632 }
633
634 prev = offset;
635 }
636 *end = prev;
637
638 return found_start;
639}
640
641/** Parse command line.
642 *
643 * @param cmdline Command line as read from input device.
644 * @param size Size (in bytes) of the string.
645 *
646 * @return Structure describing the command.
647 *
648 */
649NO_TRACE static cmd_info_t *parse_cmdline(const char *cmdline, size_t size)
650{
651 size_t start = 0;
652 size_t end = 0;
653 if (!parse_argument(cmdline, size, &start, &end)) {
654 /* Command line did not contain alphanumeric word. */
655 return NULL;
656 }
657 spinlock_lock(&cmd_lock);
658
659 cmd_info_t *cmd = NULL;
660
661 list_foreach(cmd_list, link, cmd_info_t, hlp) {
662 spinlock_lock(&hlp->lock);
663
664 if (str_lcmp(hlp->name, cmdline + start,
665 max(str_length(hlp->name),
666 str_nlength(cmdline + start, (size_t) (end - start)))) == 0) {
667 cmd = hlp;
668 break;
669 }
670
671 spinlock_unlock(&hlp->lock);
672 }
673
674 spinlock_unlock(&cmd_lock);
675
676 if (!cmd) {
677 /* Unknown command. */
678 printf("Unknown command.\n");
679 return NULL;
680 }
681
682 /* cmd == hlp is locked */
683
684 /*
685 * The command line must be further analyzed and
686 * the parameters therefrom must be matched and
687 * converted to those specified in the cmd info
688 * structure.
689 */
690
691 bool error = false;
692 size_t i;
693 for (i = 0; i < cmd->argc; i++) {
694 char *buf;
695
696 start = end;
697 if (!parse_argument(cmdline, size, &start, &end)) {
698 if (cmd->argv[i].type == ARG_TYPE_STRING_OPTIONAL) {
699 buf = (char *) cmd->argv[i].buffer;
700 str_cpy(buf, cmd->argv[i].len, "");
701 continue;
702 }
703
704 printf("Too few arguments.\n");
705 spinlock_unlock(&cmd->lock);
706 return NULL;
707 }
708
709 switch (cmd->argv[i].type) {
710 case ARG_TYPE_STRING:
711 case ARG_TYPE_STRING_OPTIONAL:
712 buf = (char *) cmd->argv[i].buffer;
713 str_ncpy(buf, cmd->argv[i].len, cmdline + start,
714 end - start);
715 break;
716 case ARG_TYPE_INT:
717 if (!parse_int_arg(cmdline + start, end - start,
718 &cmd->argv[i].intval))
719 error = true;
720 break;
721 case ARG_TYPE_VAR:
722 if ((start < end - 1) && (cmdline[start] == '"')) {
723 if (cmdline[end - 1] == '"') {
724 buf = (char *) cmd->argv[i].buffer;
725 str_ncpy(buf, cmd->argv[i].len,
726 cmdline + start + 1,
727 (end - start) - 1);
728 cmd->argv[i].intval = (sysarg_t) buf;
729 cmd->argv[i].vartype = ARG_TYPE_STRING;
730 } else {
731 printf("Wrong syntax.\n");
732 error = true;
733 }
734 } else if (parse_int_arg(cmdline + start,
735 end - start, &cmd->argv[i].intval)) {
736 cmd->argv[i].vartype = ARG_TYPE_INT;
737 } else {
738 printf("Unrecognized variable argument.\n");
739 error = true;
740 }
741 break;
742 case ARG_TYPE_INVALID:
743 default:
744 printf("Invalid argument type\n");
745 error = true;
746 break;
747 }
748 }
749
750 if (error) {
751 spinlock_unlock(&cmd->lock);
752 return NULL;
753 }
754
755 start = end;
756 if (parse_argument(cmdline, size, &start, &end)) {
757 printf("Too many arguments.\n");
758 spinlock_unlock(&cmd->lock);
759 return NULL;
760 }
761
762 spinlock_unlock(&cmd->lock);
763 return cmd;
764}
765
766/** Kernel console prompt.
767 *
768 * @param prompt Kernel console prompt (e.g kconsole/panic).
769 * @param msg Message to display in the beginning.
770 * @param kcon Wait for keypress to show the prompt
771 * and never exit.
772 *
773 */
774void kconsole(const char *prompt, const char *msg, bool kcon)
775{
776 if (!stdin) {
777 LOG("No stdin for kernel console");
778 return;
779 }
780
781 if (msg)
782 printf("%s", msg);
783
784 if (kcon)
785 indev_pop_character(stdin);
786 else
787 printf("Type \"exit\" to leave the console.\n");
788
789 char *cmdline = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
790 while (true) {
791 wchar_t *tmp = clever_readline((char *) prompt, stdin);
792 size_t len = wstr_length(tmp);
793 if (!len)
794 continue;
795
796 wstr_to_str(cmdline, STR_BOUNDS(MAX_CMDLINE), tmp);
797
798 if ((!kcon) && (len == 4) && (str_lcmp(cmdline, "exit", 4) == 0))
799 break;
800
801 cmd_info_t *cmd_info = parse_cmdline(cmdline, STR_BOUNDS(MAX_CMDLINE));
802 if (!cmd_info)
803 continue;
804
805 (void) cmd_info->func(cmd_info->argv);
806 }
807 free(cmdline);
808}
809
810/** Kernel console managing thread.
811 *
812 */
813void kconsole_thread(void *data)
814{
815 kconsole("kconsole", "Kernel console ready (press any key to activate)\n", true);
816}
817
818/** @}
819 */
Note: See TracBrowser for help on using the repository browser.