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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 6b99156 was da68871a, checked in by Adam Hraska <adam.hraska+hos@…>, 13 years ago

Merged changes from mainline.

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