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

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

tab arguments completion: defined and handled hints_enum callback in cmd_info_t

  • 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 */
167NO_TRACE static const char *cmdtab_enum(const char *name,
168 const char **h, void **ctx)
169{
170 link_t **startpos = (link_t**)ctx;
171 size_t namelen = str_length(name);
172
173 spinlock_lock(&cmd_lock);
174
175 if (*startpos == NULL)
176 *startpos = cmd_list.head.next;
177
178 for (; *startpos != &cmd_list.head; *startpos = (*startpos)->next) {
179 cmd_info_t *hlp = list_get_instance(*startpos, cmd_info_t, link);
180
181 const char *curname = hlp->name;
182 if (str_length(curname) < namelen)
183 continue;
184
185 if (str_lcmp(curname, name, namelen) == 0) {
186 *startpos = (*startpos)->next;
187 if (h) {
188 *h = hlp->description;
189 }
190 spinlock_unlock(&cmd_lock);
191 return (curname + str_lsize(curname, namelen));
192 }
193 }
194
195 spinlock_unlock(&cmd_lock);
196 return NULL;
197}
198
199/** Command completion of the commands
200 *
201 * @param name String to match, changed to hint on exit
202 * @param size Input buffer size
203 *
204 * @return Number of found matches
205 *
206 */
207NO_TRACE static int cmdtab_compl(char *input, size_t size, indev_t *indev,
208 hints_enum_func_t hints_enum)
209{
210 const char *name = input;
211
212 size_t found = 0;
213
214 /*
215 * Maximum Match Length: Length of longest matching common
216 * substring in case more than one match is found.
217 */
218 size_t max_match_len = size;
219 size_t max_match_len_tmp = size;
220 void *pos = NULL;
221 const char *hint;
222 const char *help;
223 char *output = malloc(MAX_CMDLINE, 0);
224 size_t hints_to_show = MAX_TAB_HINTS - 1;
225 size_t total_hints_shown = 0;
226 bool continue_showing_hints = true;
227
228 output[0] = 0;
229
230 while ((hint = hints_enum(name, NULL, &pos))) {
231 if ((found == 0) || (str_length(output) > str_length(hint)))
232 str_cpy(output, MAX_CMDLINE, hint);
233
234 found++;
235 }
236
237 /*
238 * If the number of possible completions is more than MAX_TAB_HINTS,
239 * ask the user whether to display them or not.
240 */
241 if (found > MAX_TAB_HINTS) {
242 printf("\n");
243 continue_showing_hints =
244 console_prompt_display_all_hints(indev, found);
245 }
246
247 if ((found > 1) && (str_length(output) != 0)) {
248 printf("\n");
249 pos = NULL;
250 while ((hint = hints_enum(name, &help, &pos))) {
251
252 if (continue_showing_hints) {
253
254 if (help)
255 printf("%s%s (%s)\n", name, hint, help);
256 else
257 printf("%s%s\n", name, hint);
258
259 --hints_to_show;
260 ++total_hints_shown;
261
262 if ((hints_to_show == 0) && (total_hints_shown != found)) {
263 /* Ask user to continue */
264 continue_showing_hints =
265 console_prompt_more_hints(indev, &hints_to_show);
266 }
267 }
268
269 for (max_match_len_tmp = 0;
270 (output[max_match_len_tmp] ==
271 hint[max_match_len_tmp]) &&
272 (max_match_len_tmp < max_match_len); ++max_match_len_tmp);
273
274 max_match_len = max_match_len_tmp;
275 }
276
277 /* Keep only the characters common in all completions */
278 output[max_match_len] = 0;
279 }
280
281 if (found > 0)
282 str_cpy(input, size, output);
283
284 free(output);
285 return found;
286}
287
288NO_TRACE static cmd_info_t *parse_cmd(const wchar_t *cmdline)
289{
290 size_t start = 0;
291 size_t end;
292 char *tmp;
293
294 while (isspace(cmdline[start]))
295 start++;
296 end = start + 1;
297 while (!isspace(cmdline[end]))
298 end++;
299
300 tmp = malloc(STR_BOUNDS(end - start + 1), 0);
301
302 wstr_to_str(tmp, end - start + 1, &cmdline[start]);
303
304 spinlock_lock(&cmd_lock);
305
306 list_foreach(cmd_list, link, cmd_info_t, hlp) {
307 spinlock_lock(&hlp->lock);
308
309 if (str_cmp(hlp->name, tmp) == 0) {
310 spinlock_unlock(&hlp->lock);
311 spinlock_unlock(&cmd_lock);
312 free(tmp);
313 return hlp;
314 }
315
316 spinlock_unlock(&hlp->lock);
317 }
318
319 free(tmp);
320 spinlock_unlock(&cmd_lock);
321
322 return NULL;
323}
324
325NO_TRACE static wchar_t *clever_readline(const char *prompt, indev_t *indev)
326{
327 printf("%s> ", prompt);
328
329 size_t position = 0;
330 wchar_t *current = history[history_pos];
331 current[0] = 0;
332 char *tmp = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
333
334 while (true) {
335 wchar_t ch = indev_pop_character(indev);
336
337 if (ch == '\n') {
338 /* Enter */
339 putchar(ch);
340 break;
341 }
342
343 if (ch == '\b') {
344 /* Backspace */
345 if (position == 0)
346 continue;
347
348 if (wstr_remove(current, position - 1)) {
349 position--;
350 putchar('\b');
351 printf("%ls ", current + position);
352 print_cc('\b', wstr_length(current) - position + 1);
353 continue;
354 }
355 }
356
357 if (ch == '\t') {
358 /* Tab completion */
359
360 /* Move to the end of the word */
361 for (; (current[position] != 0) && (!isspace(current[position]));
362 position++)
363 putchar(current[position]);
364
365 if (position == 0)
366 continue;
367
368 /*
369 * Find the beginning of the word
370 * and copy it to tmp
371 */
372 size_t beg;
373 for (beg = position - 1; (beg > 0) && (!isspace(current[beg]));
374 beg--);
375
376 if (isspace(current[beg]))
377 beg++;
378
379 wstr_to_str(tmp, position - beg + 1, current + beg);
380
381 int found;
382 if (beg == 0) {
383 /* Command completion */
384 found = cmdtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev,
385 cmdtab_enum);
386 } else {
387 /* Arguments completion */
388 cmd_info_t *cmd = parse_cmd(current);
389 if (!cmd || !cmd->hints_enum)
390 continue;
391 found = cmdtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev,
392 cmd->hints_enum);
393 }
394
395 if (found == 0)
396 continue;
397
398 /*
399 * We have hints, possibly many. In case of more than one hint,
400 * tmp will contain the common prefix.
401 */
402 size_t off = 0;
403 size_t i = 0;
404 while ((ch = str_decode(tmp, &off, STR_NO_LIMIT)) != 0) {
405 if (!wstr_linsert(current, ch, position + i, MAX_CMDLINE))
406 break;
407
408 i++;
409 }
410
411 if (found > 1) {
412 /* No unique hint, list was printed */
413 printf("%s> ", prompt);
414 printf("%ls", current);
415 position += str_length(tmp);
416 print_cc('\b', wstr_length(current) - position);
417 continue;
418 }
419
420 /* We have a hint */
421
422 printf("%ls", current + position);
423 position += str_length(tmp);
424 print_cc('\b', wstr_length(current) - position);
425
426 if (position == wstr_length(current)) {
427 /* Insert a space after the last completed argument */
428 if (wstr_linsert(current, ' ', position, MAX_CMDLINE)) {
429 printf("%ls", current + position);
430 position++;
431 }
432 }
433 continue;
434 }
435
436 if (ch == U_LEFT_ARROW) {
437 /* Left */
438 if (position > 0) {
439 putchar('\b');
440 position--;
441 }
442 continue;
443 }
444
445 if (ch == U_RIGHT_ARROW) {
446 /* Right */
447 if (position < wstr_length(current)) {
448 putchar(current[position]);
449 position++;
450 }
451 continue;
452 }
453
454 if ((ch == U_UP_ARROW) || (ch == U_DOWN_ARROW)) {
455 /* Up, down */
456 print_cc('\b', position);
457 print_cc(' ', wstr_length(current));
458 print_cc('\b', wstr_length(current));
459
460 if (ch == U_UP_ARROW) {
461 /* Up */
462 if (history_pos == 0)
463 history_pos = KCONSOLE_HISTORY - 1;
464 else
465 history_pos--;
466 } else {
467 /* Down */
468 history_pos++;
469 history_pos = history_pos % KCONSOLE_HISTORY;
470 }
471 current = history[history_pos];
472 printf("%ls", current);
473 position = wstr_length(current);
474 continue;
475 }
476
477 if (ch == U_HOME_ARROW) {
478 /* Home */
479 print_cc('\b', position);
480 position = 0;
481 continue;
482 }
483
484 if (ch == U_END_ARROW) {
485 /* End */
486 printf("%ls", current + position);
487 position = wstr_length(current);
488 continue;
489 }
490
491 if (ch == U_DELETE) {
492 /* Delete */
493 if (position == wstr_length(current))
494 continue;
495
496 if (wstr_remove(current, position)) {
497 printf("%ls ", current + position);
498 print_cc('\b', wstr_length(current) - position + 1);
499 }
500 continue;
501 }
502
503 if (wstr_linsert(current, ch, position, MAX_CMDLINE)) {
504 printf("%ls", current + position);
505 position++;
506 print_cc('\b', wstr_length(current) - position);
507 }
508 }
509
510 if (wstr_length(current) > 0) {
511 history_pos++;
512 history_pos = history_pos % KCONSOLE_HISTORY;
513 }
514
515 free(tmp);
516 return current;
517}
518
519bool kconsole_check_poll(void)
520{
521 return check_poll(stdin);
522}
523
524NO_TRACE static bool parse_int_arg(const char *text, size_t len,
525 sysarg_t *result)
526{
527 bool isaddr = false;
528 bool isptr = false;
529
530 /* If we get a name, try to find it in symbol table */
531 if (text[0] == '&') {
532 isaddr = true;
533 text++;
534 len--;
535 } else if (text[0] == '*') {
536 isptr = true;
537 text++;
538 len--;
539 }
540
541 if ((text[0] < '0') || (text[0] > '9')) {
542 char symname[MAX_SYMBOL_NAME];
543 str_ncpy(symname, MAX_SYMBOL_NAME, text, len + 1);
544
545 uintptr_t symaddr;
546 int rc = symtab_addr_lookup(symname, &symaddr);
547 switch (rc) {
548 case ENOENT:
549 printf("Symbol %s not found.\n", symname);
550 return false;
551 case EOVERFLOW:
552 printf("Duplicate symbol %s.\n", symname);
553 symtab_print_search(symname);
554 return false;
555 case ENOTSUP:
556 printf("No symbol information available.\n");
557 return false;
558 case EOK:
559 if (isaddr)
560 *result = (sysarg_t) symaddr;
561 else if (isptr)
562 *result = **((sysarg_t **) symaddr);
563 else
564 *result = *((sysarg_t *) symaddr);
565 break;
566 default:
567 printf("Unknown error.\n");
568 return false;
569 }
570 } else {
571 /* It's a number - convert it */
572 uint64_t value;
573 char *end;
574 int rc = str_uint64_t(text, &end, 0, false, &value);
575 if (end != text + len)
576 rc = EINVAL;
577 switch (rc) {
578 case EINVAL:
579 printf("Invalid number '%s'.\n", text);
580 return false;
581 case EOVERFLOW:
582 printf("Integer overflow in '%s'.\n", text);
583 return false;
584 case EOK:
585 *result = (sysarg_t) value;
586 if (isptr)
587 *result = *((sysarg_t *) *result);
588 break;
589 default:
590 printf("Unknown error parsing '%s'.\n", text);
591 return false;
592 }
593 }
594
595 return true;
596}
597
598/** Parse argument.
599 *
600 * Find start and end positions of command line argument.
601 *
602 * @param cmdline Command line as read from the input device.
603 * @param size Size (in bytes) of the string.
604 * @param start On entry, 'start' contains pointer to the offset
605 * of the first unprocessed character of cmdline.
606 * On successful exit, it marks beginning of the next argument.
607 * @param end Undefined on entry. On exit, 'end' is the offset of the first
608 * character behind the next argument.
609 *
610 * @return False on failure, true on success.
611 *
612 */
613NO_TRACE static bool parse_argument(const char *cmdline, size_t size,
614 size_t *start, size_t *end)
615{
616 ASSERT(start != NULL);
617 ASSERT(end != NULL);
618
619 bool found_start = false;
620 size_t offset = *start;
621 size_t prev = *start;
622 wchar_t ch;
623
624 while ((ch = str_decode(cmdline, &offset, size)) != 0) {
625 if (!found_start) {
626 if (!isspace(ch)) {
627 *start = prev;
628 found_start = true;
629 }
630 } else {
631 if (isspace(ch))
632 break;
633 }
634
635 prev = offset;
636 }
637 *end = prev;
638
639 return found_start;
640}
641
642/** Parse command line.
643 *
644 * @param cmdline Command line as read from input device.
645 * @param size Size (in bytes) of the string.
646 *
647 * @return Structure describing the command.
648 *
649 */
650NO_TRACE static cmd_info_t *parse_cmdline(const char *cmdline, size_t size)
651{
652 size_t start = 0;
653 size_t end = 0;
654 if (!parse_argument(cmdline, size, &start, &end)) {
655 /* Command line did not contain alphanumeric word. */
656 return NULL;
657 }
658 spinlock_lock(&cmd_lock);
659
660 cmd_info_t *cmd = NULL;
661
662 list_foreach(cmd_list, link, cmd_info_t, hlp) {
663 spinlock_lock(&hlp->lock);
664
665 if (str_lcmp(hlp->name, cmdline + start,
666 max(str_length(hlp->name),
667 str_nlength(cmdline + start, (size_t) (end - start)))) == 0) {
668 cmd = hlp;
669 break;
670 }
671
672 spinlock_unlock(&hlp->lock);
673 }
674
675 spinlock_unlock(&cmd_lock);
676
677 if (!cmd) {
678 /* Unknown command. */
679 printf("Unknown command.\n");
680 return NULL;
681 }
682
683 /* cmd == hlp is locked */
684
685 /*
686 * The command line must be further analyzed and
687 * the parameters therefrom must be matched and
688 * converted to those specified in the cmd info
689 * structure.
690 */
691
692 bool error = false;
693 size_t i;
694 for (i = 0; i < cmd->argc; i++) {
695 char *buf;
696
697 start = end;
698 if (!parse_argument(cmdline, size, &start, &end)) {
699 if (cmd->argv[i].type == ARG_TYPE_STRING_OPTIONAL) {
700 buf = (char *) cmd->argv[i].buffer;
701 str_cpy(buf, cmd->argv[i].len, "");
702 continue;
703 }
704
705 printf("Too few arguments.\n");
706 spinlock_unlock(&cmd->lock);
707 return NULL;
708 }
709
710 switch (cmd->argv[i].type) {
711 case ARG_TYPE_STRING:
712 case ARG_TYPE_STRING_OPTIONAL:
713 buf = (char *) cmd->argv[i].buffer;
714 str_ncpy(buf, cmd->argv[i].len, cmdline + start,
715 end - start);
716 break;
717 case ARG_TYPE_INT:
718 if (!parse_int_arg(cmdline + start, end - start,
719 &cmd->argv[i].intval))
720 error = true;
721 break;
722 case ARG_TYPE_VAR:
723 if ((start < end - 1) && (cmdline[start] == '"')) {
724 if (cmdline[end - 1] == '"') {
725 buf = (char *) cmd->argv[i].buffer;
726 str_ncpy(buf, cmd->argv[i].len,
727 cmdline + start + 1,
728 (end - start) - 1);
729 cmd->argv[i].intval = (sysarg_t) buf;
730 cmd->argv[i].vartype = ARG_TYPE_STRING;
731 } else {
732 printf("Wrong syntax.\n");
733 error = true;
734 }
735 } else if (parse_int_arg(cmdline + start,
736 end - start, &cmd->argv[i].intval)) {
737 cmd->argv[i].vartype = ARG_TYPE_INT;
738 } else {
739 printf("Unrecognized variable argument.\n");
740 error = true;
741 }
742 break;
743 case ARG_TYPE_INVALID:
744 default:
745 printf("Invalid argument type\n");
746 error = true;
747 break;
748 }
749 }
750
751 if (error) {
752 spinlock_unlock(&cmd->lock);
753 return NULL;
754 }
755
756 start = end;
757 if (parse_argument(cmdline, size, &start, &end)) {
758 printf("Too many arguments.\n");
759 spinlock_unlock(&cmd->lock);
760 return NULL;
761 }
762
763 spinlock_unlock(&cmd->lock);
764 return cmd;
765}
766
767/** Kernel console prompt.
768 *
769 * @param prompt Kernel console prompt (e.g kconsole/panic).
770 * @param msg Message to display in the beginning.
771 * @param kcon Wait for keypress to show the prompt
772 * and never exit.
773 *
774 */
775void kconsole(const char *prompt, const char *msg, bool kcon)
776{
777 if (!stdin) {
778 LOG("No stdin for kernel console");
779 return;
780 }
781
782 if (msg)
783 printf("%s", msg);
784
785 if (kcon)
786 indev_pop_character(stdin);
787 else
788 printf("Type \"exit\" to leave the console.\n");
789
790 char *cmdline = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
791 while (true) {
792 wchar_t *tmp = clever_readline((char *) prompt, stdin);
793 size_t len = wstr_length(tmp);
794 if (!len)
795 continue;
796
797 wstr_to_str(cmdline, STR_BOUNDS(MAX_CMDLINE), tmp);
798
799 if ((!kcon) && (len == 4) && (str_lcmp(cmdline, "exit", 4) == 0))
800 break;
801
802 cmd_info_t *cmd_info = parse_cmdline(cmdline, STR_BOUNDS(MAX_CMDLINE));
803 if (!cmd_info)
804 continue;
805
806 (void) cmd_info->func(cmd_info->argv);
807 }
808 free(cmdline);
809}
810
811/** Kernel console managing thread.
812 *
813 */
814void kconsole_thread(void *data)
815{
816 kconsole("kconsole", "Kernel console ready (press any key to activate)\n", true);
817}
818
819/** @}
820 */
Note: See TracBrowser for help on using the repository browser.