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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since bf9cb2f was feeac0d, checked in by Jiri Svoboda <jiri@…>, 12 years ago

Simplify use of list_foreach.

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