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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since a7d8739 was a7d8739, checked in by Jan Vesely <jano.vesely@…>, 13 years ago

kconsole: Be more verbose in reporting integer parsing errors.

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