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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since e8d6ce2 was a1ecb88, checked in by Martin Decky <martin@…>, 12 years ago

remove duplicate include

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