Symbol table completion for kernel console (#50)
[helenos.git] / kernel / generic / src / console / kconsole.c
blob81d6ea4306abb55393779ab2001309d7c5ebcf5e
1 /*
2 * Copyright (c) 2005 Jakub Jermar
3 * All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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.
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.
29 /** @addtogroup genericconsole
30 * @{
33 /**
34 * @file kconsole.c
35 * @brief Kernel console.
37 * This file contains kernel thread managing the kernel console.
41 #include <console/kconsole.h>
42 #include <console/console.h>
43 #include <console/chardev.h>
44 #include <console/cmd.h>
45 #include <print.h>
46 #include <panic.h>
47 #include <typedefs.h>
48 #include <adt/list.h>
49 #include <arch.h>
50 #include <macros.h>
51 #include <debug.h>
52 #include <func.h>
53 #include <str.h>
54 #include <macros.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>
62 /** Simple kernel console.
64 * The console is realized by kernel thread kconsole.
65 * It doesn't understand any useful command on its own,
66 * but makes it possible for other kernel subsystems to
67 * register their own commands.
70 /** Locking.
72 * There is a list of cmd_info_t structures. This list
73 * is protected by cmd_lock spinlock. Note that specially
74 * the link elements of cmd_info_t are protected by
75 * this lock.
77 * Each cmd_info_t also has its own lock, which protects
78 * all elements thereof except the link element.
80 * cmd_lock must be acquired before any cmd_info lock.
81 * When locking two cmd info structures, structure with
82 * lower address must be locked first.
85 SPINLOCK_INITIALIZE(cmd_lock); /**< Lock protecting command list. */
86 LIST_INITIALIZE(cmd_list); /**< Command list. */
88 static wchar_t history[KCONSOLE_HISTORY][MAX_CMDLINE] = {};
89 static size_t history_pos = 0;
91 /** Initialize kconsole data structures
93 * This is the most basic initialization, almost no
94 * other kernel subsystem is ready yet.
97 void kconsole_init(void)
99 unsigned int i;
101 cmd_init();
102 for (i = 0; i < KCONSOLE_HISTORY; i++)
103 history[i][0] = 0;
106 /** Register kconsole command.
108 * @param cmd Structure describing the command.
110 * @return False on failure, true on success.
113 bool cmd_register(cmd_info_t *cmd)
115 spinlock_lock(&cmd_lock);
118 * Make sure the command is not already listed.
120 list_foreach(cmd_list, cur) {
121 cmd_info_t *hlp = list_get_instance(cur, cmd_info_t, link);
123 if (hlp == cmd) {
124 /* The command is already there. */
125 spinlock_unlock(&cmd_lock);
126 return false;
129 /* Avoid deadlock. */
130 if (hlp < cmd) {
131 spinlock_lock(&hlp->lock);
132 spinlock_lock(&cmd->lock);
133 } else {
134 spinlock_lock(&cmd->lock);
135 spinlock_lock(&hlp->lock);
138 if (str_cmp(hlp->name, cmd->name) == 0) {
139 /* The command is already there. */
140 spinlock_unlock(&hlp->lock);
141 spinlock_unlock(&cmd->lock);
142 spinlock_unlock(&cmd_lock);
143 return false;
146 spinlock_unlock(&hlp->lock);
147 spinlock_unlock(&cmd->lock);
151 * Now the command can be added.
153 list_append(&cmd->link, &cmd_list);
155 spinlock_unlock(&cmd_lock);
156 return true;
159 /** Print count times a character */
160 NO_TRACE static void print_cc(wchar_t ch, size_t count)
162 size_t i;
163 for (i = 0; i < count; i++)
164 putchar(ch);
167 /** Try to find a command beginning with prefix */
168 NO_TRACE static const char *cmdtab_search_one(const char *name,
169 link_t **startpos)
171 size_t namelen = str_length(name);
173 spinlock_lock(&cmd_lock);
175 if (*startpos == NULL)
176 *startpos = cmd_list.head.next;
178 for (; *startpos != &cmd_list.head; *startpos = (*startpos)->next) {
179 cmd_info_t *hlp = list_get_instance(*startpos, cmd_info_t, link);
181 const char *curname = hlp->name;
182 if (str_length(curname) < namelen)
183 continue;
185 if (str_lcmp(curname, name, namelen) == 0) {
186 spinlock_unlock(&cmd_lock);
187 return (curname + str_lsize(curname, namelen));
191 spinlock_unlock(&cmd_lock);
192 return NULL;
195 /** Command completion of the commands
197 * @param name String to match, changed to hint on exit
198 * @param size Input buffer size
200 * @return Number of found matches
203 NO_TRACE static int cmdtab_compl(char *input, size_t size, indev_t * indev)
205 const char *name = input;
207 size_t found = 0;
208 /* Maximum Match Length : Length of longest matching common substring in
209 case more than one match is found */
210 size_t max_match_len = size;
211 size_t max_match_len_tmp = size;
212 size_t input_len = str_length(input);
213 link_t *pos = NULL;
214 const char *hint;
215 char *output = malloc(MAX_CMDLINE, 0);
216 char display = 'y';
217 size_t hints_to_show = MAX_TAB_HINTS - 1;
218 size_t total_hints_shown = 0;
219 char continue_showing_hints = 'y';
221 output[0] = 0;
223 while ((hint = cmdtab_search_one(name, &pos))) {
224 if ((found == 0) || (str_length(output) > str_length(hint)))
225 str_cpy(output, MAX_CMDLINE, hint);
227 pos = pos->next;
228 found++;
231 /* If possible completions are more than MAX_TAB_HINTS, ask user whether to display them or not. */
232 if (found > MAX_TAB_HINTS) {
233 printf("\nDisplay all %zu possibilities? (y or n)", found);
234 do {
235 display = indev_pop_character(indev);
236 } while (display != 'y' && display != 'n' && display != 'Y' && display != 'N');
239 if ((found > 1) && (str_length(output) != 0)) {
240 printf("\n");
241 pos = NULL;
242 while (cmdtab_search_one(name, &pos)) {
243 cmd_info_t *hlp = list_get_instance(pos, cmd_info_t, link);
245 if (display == 'y' || display == 'Y') { /* We are still showing hints */
246 printf("%s (%s)\n", hlp->name, hlp->description);
247 --hints_to_show;
248 ++total_hints_shown;
250 if (hints_to_show == 0 && total_hints_shown != found) { /* Time to ask user to continue */
251 printf("--More--");
252 do {
253 continue_showing_hints = indev_pop_character(indev);
254 if (continue_showing_hints == 'y' || continue_showing_hints == 'Y'
255 || continue_showing_hints == ' ') {
256 hints_to_show = MAX_TAB_HINTS - 1; /* Display a full page again */
257 break;
260 if (continue_showing_hints == 'n' || continue_showing_hints == 'N'
261 || continue_showing_hints == 'q' || continue_showing_hints == 'Q') {
262 display = 'n'; /* Stop displaying hints */
263 break;
266 if (continue_showing_hints == '\n') {
267 hints_to_show = 1; /* Show one more hint */
268 break;
270 } while (1);
272 printf("\r \r"); /* Delete the --More-- option */
276 pos = pos->next;
277 for(max_match_len_tmp = 0; output[max_match_len_tmp] == hlp->name[input_len + max_match_len_tmp]
278 && max_match_len_tmp < max_match_len; ++max_match_len_tmp);
279 max_match_len = max_match_len_tmp;
281 /* keep only the characters common in all completions */
282 output[max_match_len] = 0;
285 if (found > 0)
286 str_cpy(input, size, output);
288 free(output);
289 return found;
292 NO_TRACE static wchar_t *clever_readline(const char *prompt, indev_t *indev)
294 printf("%s> ", prompt);
296 size_t position = 0;
297 wchar_t *current = history[history_pos];
298 current[0] = 0;
299 char *tmp = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
301 while (true) {
302 wchar_t ch = indev_pop_character(indev);
304 if (ch == '\n') {
305 /* Enter */
306 putchar(ch);
307 break;
310 if (ch == '\b') {
311 /* Backspace */
312 if (position == 0)
313 continue;
315 if (wstr_remove(current, position - 1)) {
316 position--;
317 putchar('\b');
318 printf("%ls ", current + position);
319 print_cc('\b', wstr_length(current) - position + 1);
320 continue;
324 if (ch == '\t') {
325 /* Tab completion */
327 /* Move to the end of the word */
328 for (; (current[position] != 0) && (!isspace(current[position]));
329 position++)
330 putchar(current[position]);
332 if (position == 0)
333 continue;
335 /* Find the beginning of the word
336 and copy it to tmp */
337 size_t beg;
338 for (beg = position - 1; (beg > 0) && (!isspace(current[beg]));
339 beg--);
341 if (isspace(current[beg]))
342 beg++;
344 wstr_to_str(tmp, position - beg + 1, current + beg);
346 int found;
347 if (beg == 0) {
348 /* Command completion */
349 found = cmdtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev);
350 } else {
351 /* Symbol completion */
352 found = symtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev);
355 if (found == 0)
356 continue;
358 /* We have hints, may be many. In case of more than one hint,
359 tmp will contain the common prefix. */
360 size_t off = 0;
361 size_t i = 0;
362 while ((ch = str_decode(tmp, &off, STR_NO_LIMIT)) != 0) {
363 if (!wstr_linsert(current, ch, position + i, MAX_CMDLINE))
364 break;
365 i++;
368 if (found > 1) {
369 /* No unique hint, list was printed */
370 printf("%s> ", prompt);
371 printf("%ls", current);
372 position += str_length(tmp);
373 print_cc('\b', wstr_length(current) - position);
374 continue;
377 /* We have a hint */
379 printf("%ls", current + position);
380 position += str_length(tmp);
381 print_cc('\b', wstr_length(current) - position);
383 if (position == wstr_length(current)) {
384 /* Insert a space after the last completed argument */
385 if (wstr_linsert(current, ' ', position, MAX_CMDLINE)) {
386 printf("%ls", current + position);
387 position++;
390 continue;
393 if (ch == U_LEFT_ARROW) {
394 /* Left */
395 if (position > 0) {
396 putchar('\b');
397 position--;
399 continue;
402 if (ch == U_RIGHT_ARROW) {
403 /* Right */
404 if (position < wstr_length(current)) {
405 putchar(current[position]);
406 position++;
408 continue;
411 if ((ch == U_UP_ARROW) || (ch == U_DOWN_ARROW)) {
412 /* Up, down */
413 print_cc('\b', position);
414 print_cc(' ', wstr_length(current));
415 print_cc('\b', wstr_length(current));
417 if (ch == U_UP_ARROW) {
418 /* Up */
419 if (history_pos == 0)
420 history_pos = KCONSOLE_HISTORY - 1;
421 else
422 history_pos--;
423 } else {
424 /* Down */
425 history_pos++;
426 history_pos = history_pos % KCONSOLE_HISTORY;
428 current = history[history_pos];
429 printf("%ls", current);
430 position = wstr_length(current);
431 continue;
434 if (ch == U_HOME_ARROW) {
435 /* Home */
436 print_cc('\b', position);
437 position = 0;
438 continue;
441 if (ch == U_END_ARROW) {
442 /* End */
443 printf("%ls", current + position);
444 position = wstr_length(current);
445 continue;
448 if (ch == U_DELETE) {
449 /* Delete */
450 if (position == wstr_length(current))
451 continue;
453 if (wstr_remove(current, position)) {
454 printf("%ls ", current + position);
455 print_cc('\b', wstr_length(current) - position + 1);
457 continue;
460 if (wstr_linsert(current, ch, position, MAX_CMDLINE)) {
461 printf("%ls", current + position);
462 position++;
463 print_cc('\b', wstr_length(current) - position);
467 if (wstr_length(current) > 0) {
468 history_pos++;
469 history_pos = history_pos % KCONSOLE_HISTORY;
472 free(tmp);
473 return current;
476 bool kconsole_check_poll(void)
478 return check_poll(stdin);
481 NO_TRACE static bool parse_int_arg(const char *text, size_t len,
482 sysarg_t *result)
484 bool isaddr = false;
485 bool isptr = false;
487 /* If we get a name, try to find it in symbol table */
488 if (text[0] == '&') {
489 isaddr = true;
490 text++;
491 len--;
492 } else if (text[0] == '*') {
493 isptr = true;
494 text++;
495 len--;
498 if ((text[0] < '0') || (text[0] > '9')) {
499 char symname[MAX_SYMBOL_NAME];
500 str_ncpy(symname, MAX_SYMBOL_NAME, text, len + 1);
502 uintptr_t symaddr;
503 int rc = symtab_addr_lookup(symname, &symaddr);
504 switch (rc) {
505 case ENOENT:
506 printf("Symbol %s not found.\n", symname);
507 return false;
508 case EOVERFLOW:
509 printf("Duplicate symbol %s.\n", symname);
510 symtab_print_search(symname);
511 return false;
512 case ENOTSUP:
513 printf("No symbol information available.\n");
514 return false;
515 case EOK:
516 if (isaddr)
517 *result = (sysarg_t) symaddr;
518 else if (isptr)
519 *result = **((sysarg_t **) symaddr);
520 else
521 *result = *((sysarg_t *) symaddr);
522 break;
523 default:
524 printf("Unknown error.\n");
525 return false;
527 } else {
528 /* It's a number - convert it */
529 uint64_t value;
530 int rc = str_uint64_t(text, NULL, 0, true, &value);
531 switch (rc) {
532 case EINVAL:
533 printf("Invalid number.\n");
534 return false;
535 case EOVERFLOW:
536 printf("Integer overflow.\n");
537 return false;
538 case EOK:
539 *result = (sysarg_t) value;
540 if (isptr)
541 *result = *((sysarg_t *) *result);
542 break;
543 default:
544 printf("Unknown error.\n");
545 return false;
549 return true;
552 /** Parse argument.
554 * Find start and end positions of command line argument.
556 * @param cmdline Command line as read from the input device.
557 * @param size Size (in bytes) of the string.
558 * @param start On entry, 'start' contains pointer to the offset
559 * of the first unprocessed character of cmdline.
560 * On successful exit, it marks beginning of the next argument.
561 * @param end Undefined on entry. On exit, 'end' is the offset of the first
562 * character behind the next argument.
564 * @return False on failure, true on success.
567 NO_TRACE static bool parse_argument(const char *cmdline, size_t size,
568 size_t *start, size_t *end)
570 ASSERT(start != NULL);
571 ASSERT(end != NULL);
573 bool found_start = false;
574 size_t offset = *start;
575 size_t prev = *start;
576 wchar_t ch;
578 while ((ch = str_decode(cmdline, &offset, size)) != 0) {
579 if (!found_start) {
580 if (!isspace(ch)) {
581 *start = prev;
582 found_start = true;
584 } else {
585 if (isspace(ch))
586 break;
589 prev = offset;
591 *end = prev;
593 return found_start;
596 /** Parse command line.
598 * @param cmdline Command line as read from input device.
599 * @param size Size (in bytes) of the string.
601 * @return Structure describing the command.
604 NO_TRACE static cmd_info_t *parse_cmdline(const char *cmdline, size_t size)
606 size_t start = 0;
607 size_t end = 0;
608 if (!parse_argument(cmdline, size, &start, &end)) {
609 /* Command line did not contain alphanumeric word. */
610 return NULL;
612 spinlock_lock(&cmd_lock);
614 cmd_info_t *cmd = NULL;
616 list_foreach(cmd_list, cur) {
617 cmd_info_t *hlp = list_get_instance(cur, cmd_info_t, link);
618 spinlock_lock(&hlp->lock);
620 if (str_lcmp(hlp->name, cmdline + start,
621 max(str_length(hlp->name),
622 str_nlength(cmdline + start, (size_t) (end - start)))) == 0) {
623 cmd = hlp;
624 break;
627 spinlock_unlock(&hlp->lock);
630 spinlock_unlock(&cmd_lock);
632 if (!cmd) {
633 /* Unknown command. */
634 printf("Unknown command.\n");
635 return NULL;
638 /* cmd == hlp is locked */
641 * The command line must be further analyzed and
642 * the parameters therefrom must be matched and
643 * converted to those specified in the cmd info
644 * structure.
647 bool error = false;
648 size_t i;
649 for (i = 0; i < cmd->argc; i++) {
650 char *buf;
652 start = end;
653 if (!parse_argument(cmdline, size, &start, &end)) {
654 if (cmd->argv[i].type == ARG_TYPE_STRING_OPTIONAL) {
655 buf = (char *) cmd->argv[i].buffer;
656 str_cpy(buf, cmd->argv[i].len, "");
657 continue;
660 printf("Too few arguments.\n");
661 spinlock_unlock(&cmd->lock);
662 return NULL;
665 switch (cmd->argv[i].type) {
666 case ARG_TYPE_STRING:
667 case ARG_TYPE_STRING_OPTIONAL:
668 buf = (char *) cmd->argv[i].buffer;
669 str_ncpy(buf, cmd->argv[i].len, cmdline + start,
670 end - start);
671 break;
672 case ARG_TYPE_INT:
673 if (!parse_int_arg(cmdline + start, end - start,
674 &cmd->argv[i].intval))
675 error = true;
676 break;
677 case ARG_TYPE_VAR:
678 if ((start < end - 1) && (cmdline[start] == '"')) {
679 if (cmdline[end - 1] == '"') {
680 buf = (char *) cmd->argv[i].buffer;
681 str_ncpy(buf, cmd->argv[i].len,
682 cmdline + start + 1,
683 (end - start) - 1);
684 cmd->argv[i].intval = (sysarg_t) buf;
685 cmd->argv[i].vartype = ARG_TYPE_STRING;
686 } else {
687 printf("Wrong syntax.\n");
688 error = true;
690 } else if (parse_int_arg(cmdline + start,
691 end - start, &cmd->argv[i].intval)) {
692 cmd->argv[i].vartype = ARG_TYPE_INT;
693 } else {
694 printf("Unrecognized variable argument.\n");
695 error = true;
697 break;
698 case ARG_TYPE_INVALID:
699 default:
700 printf("Invalid argument type\n");
701 error = true;
702 break;
706 if (error) {
707 spinlock_unlock(&cmd->lock);
708 return NULL;
711 start = end;
712 if (parse_argument(cmdline, size, &start, &end)) {
713 printf("Too many arguments.\n");
714 spinlock_unlock(&cmd->lock);
715 return NULL;
718 spinlock_unlock(&cmd->lock);
719 return cmd;
722 /** Kernel console prompt.
724 * @param prompt Kernel console prompt (e.g kconsole/panic).
725 * @param msg Message to display in the beginning.
726 * @param kcon Wait for keypress to show the prompt
727 * and never exit.
730 void kconsole(const char *prompt, const char *msg, bool kcon)
732 if (!stdin) {
733 LOG("No stdin for kernel console");
734 return;
737 if (msg)
738 printf("%s", msg);
740 if (kcon)
741 indev_pop_character(stdin);
742 else
743 printf("Type \"exit\" to leave the console.\n");
745 char *cmdline = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
746 while (true) {
747 wchar_t *tmp = clever_readline((char *) prompt, stdin);
748 size_t len = wstr_length(tmp);
749 if (!len)
750 continue;
752 wstr_to_str(cmdline, STR_BOUNDS(MAX_CMDLINE), tmp);
754 if ((!kcon) && (len == 4) && (str_lcmp(cmdline, "exit", 4) == 0))
755 break;
757 cmd_info_t *cmd_info = parse_cmdline(cmdline, STR_BOUNDS(MAX_CMDLINE));
758 if (!cmd_info)
759 continue;
761 (void) cmd_info->func(cmd_info->argv);
763 free(cmdline);
766 /** Kernel console managing thread.
769 void kconsole_thread(void *data)
771 kconsole("kconsole", "Kernel console ready (press any key to activate)\n", true);
774 /** @}