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

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 6afc9d7 was b1c57a8, checked in by Jakub Jermar <jakub@…>, 11 years ago

Merge from lp:~adam-hraska+lp/helenos/rcu/.

Only merge from the feature branch and resolve all conflicts.

  • 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#include <mm/slab.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, link, cmd_info_t, hlp) {
122 if (hlp == cmd) {
123 /* The command is already there. */
124 spinlock_unlock(&cmd_lock);
125 return false;
126 }
127
128 /* Avoid deadlock. */
129 if (hlp < cmd) {
130 spinlock_lock(&hlp->lock);
131 spinlock_lock(&cmd->lock);
132 } else {
133 spinlock_lock(&cmd->lock);
134 spinlock_lock(&hlp->lock);
135 }
136
137 if (str_cmp(hlp->name, cmd->name) == 0) {
138 /* The command is already there. */
139 spinlock_unlock(&hlp->lock);
140 spinlock_unlock(&cmd->lock);
141 spinlock_unlock(&cmd_lock);
142 return false;
143 }
144
145 spinlock_unlock(&hlp->lock);
146 spinlock_unlock(&cmd->lock);
147 }
148
149 /*
150 * Now the command can be added.
151 */
152 list_append(&cmd->link, &cmd_list);
153
154 spinlock_unlock(&cmd_lock);
155 return true;
156}
157
158/** Print count times a character */
159NO_TRACE static void print_cc(wchar_t ch, size_t count)
160{
161 size_t i;
162 for (i = 0; i < count; i++)
163 putchar(ch);
164}
165
166/** Try to find a command beginning with prefix */
167NO_TRACE static const char *cmdtab_search_one(const char *name,
168 link_t **startpos)
169{
170 size_t namelen = str_length(name);
171
172 spinlock_lock(&cmd_lock);
173
174 if (*startpos == NULL)
175 *startpos = cmd_list.head.next;
176
177 for (; *startpos != &cmd_list.head; *startpos = (*startpos)->next) {
178 cmd_info_t *hlp = list_get_instance(*startpos, cmd_info_t, link);
179
180 const char *curname = hlp->name;
181 if (str_length(curname) < namelen)
182 continue;
183
184 if (str_lcmp(curname, name, namelen) == 0) {
185 spinlock_unlock(&cmd_lock);
186 return (curname + str_lsize(curname, namelen));
187 }
188 }
189
190 spinlock_unlock(&cmd_lock);
191 return NULL;
192}
193
194/** Command completion of the commands
195 *
196 * @param name String to match, changed to hint on exit
197 * @param size Input buffer size
198 *
199 * @return Number of found matches
200 *
201 */
202NO_TRACE static int cmdtab_compl(char *input, size_t size, indev_t *indev)
203{
204 const char *name = input;
205
206 size_t found = 0;
207
208 /*
209 * Maximum Match Length: Length of longest matching common
210 * substring in case more than one match is found.
211 */
212 size_t max_match_len = size;
213 size_t max_match_len_tmp = size;
214 size_t input_len = str_length(input);
215 link_t *pos = NULL;
216 const char *hint;
217 char *output = malloc(MAX_CMDLINE, 0);
218 size_t hints_to_show = MAX_TAB_HINTS - 1;
219 size_t total_hints_shown = 0;
220 bool continue_showing_hints = true;
221
222 output[0] = 0;
223
224 while ((hint = cmdtab_search_one(name, &pos))) {
225 if ((found == 0) || (str_length(output) > str_length(hint)))
226 str_cpy(output, MAX_CMDLINE, hint);
227
228 pos = pos->next;
229 found++;
230 }
231
232 /*
233 * If the number of possible completions is more than MAX_TAB_HINTS,
234 * ask the user whether to display them or not.
235 */
236 if (found > MAX_TAB_HINTS) {
237 printf("\n");
238 continue_showing_hints =
239 console_prompt_display_all_hints(indev, found);
240 }
241
242 if ((found > 1) && (str_length(output) != 0)) {
243 printf("\n");
244 pos = NULL;
245 while (cmdtab_search_one(name, &pos)) {
246 cmd_info_t *hlp = list_get_instance(pos, cmd_info_t, link);
247
248 if (continue_showing_hints) {
249 printf("%s (%s)\n", hlp->name, hlp->description);
250 --hints_to_show;
251 ++total_hints_shown;
252
253 if ((hints_to_show == 0) && (total_hints_shown != found)) {
254 /* Ask user to continue */
255 continue_showing_hints =
256 console_prompt_more_hints(indev, &hints_to_show);
257 }
258 }
259
260 pos = pos->next;
261
262 for (max_match_len_tmp = 0;
263 (output[max_match_len_tmp] ==
264 hlp->name[input_len + max_match_len_tmp]) &&
265 (max_match_len_tmp < max_match_len); ++max_match_len_tmp);
266
267 max_match_len = max_match_len_tmp;
268 }
269
270 /* Keep only the characters common in all completions */
271 output[max_match_len] = 0;
272 }
273
274 if (found > 0)
275 str_cpy(input, size, output);
276
277 free(output);
278 return found;
279}
280
281NO_TRACE static wchar_t *clever_readline(const char *prompt, indev_t *indev)
282{
283 printf("%s> ", prompt);
284
285 size_t position = 0;
286 wchar_t *current = history[history_pos];
287 current[0] = 0;
288 char *tmp = malloc(STR_BOUNDS(MAX_CMDLINE), 0);
289
290 while (true) {
291 wchar_t ch = indev_pop_character(indev);
292
293 if (ch == '\n') {
294 /* Enter */
295 putchar(ch);
296 break;
297 }
298
299 if (ch == '\b') {
300 /* Backspace */
301 if (position == 0)
302 continue;
303
304 if (wstr_remove(current, position - 1)) {
305 position--;
306 putchar('\b');
307 printf("%ls ", current + position);
308 print_cc('\b', wstr_length(current) - position + 1);
309 continue;
310 }
311 }
312
313 if (ch == '\t') {
314 /* Tab completion */
315
316 /* Move to the end of the word */
317 for (; (current[position] != 0) && (!isspace(current[position]));
318 position++)
319 putchar(current[position]);
320
321 if (position == 0)
322 continue;
323
324 /*
325 * Find the beginning of the word
326 * and copy it to tmp
327 */
328 size_t beg;
329 for (beg = position - 1; (beg > 0) && (!isspace(current[beg]));
330 beg--);
331
332 if (isspace(current[beg]))
333 beg++;
334
335 wstr_to_str(tmp, position - beg + 1, current + beg);
336
337 int found;
338 if (beg == 0) {
339 /* Command completion */
340 found = cmdtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev);
341 } else {
342 /* Symbol completion */
343 found = symtab_compl(tmp, STR_BOUNDS(MAX_CMDLINE), indev);
344 }
345
346 if (found == 0)
347 continue;
348
349 /*
350 * We have hints, possibly many. In case of more than one hint,
351 * tmp will contain the common prefix.
352 */
353 size_t off = 0;
354 size_t i = 0;
355 while ((ch = str_decode(tmp, &off, STR_NO_LIMIT)) != 0) {
356 if (!wstr_linsert(current, ch, position + i, MAX_CMDLINE))
357 break;
358
359 i++;
360 }
361
362 if (found > 1) {
363 /* No unique hint, list was printed */
364 printf("%s> ", prompt);
365 printf("%ls", current);
366 position += str_length(tmp);
367 print_cc('\b', wstr_length(current) - position);
368 continue;
369 }
370
371 /* We have a hint */
372
373 printf("%ls", current + position);
374 position += str_length(tmp);
375 print_cc('\b', wstr_length(current) - position);
376
377 if (position == wstr_length(current)) {
378 /* Insert a space after the last completed argument */
379 if (wstr_linsert(current, ' ', position, MAX_CMDLINE)) {
380 printf("%ls", current + position);
381 position++;
382 }
383 }
384 continue;
385 }
386
387 if (ch == U_LEFT_ARROW) {
388 /* Left */
389 if (position > 0) {
390 putchar('\b');
391 position--;
392 }
393 continue;
394 }
395
396 if (ch == U_RIGHT_ARROW) {
397 /* Right */
398 if (position < wstr_length(current)) {
399 putchar(current[position]);
400 position++;
401 }
402 continue;
403 }
404
405 if ((ch == U_UP_ARROW) || (ch == U_DOWN_ARROW)) {
406 /* Up, down */
407 print_cc('\b', position);
408 print_cc(' ', wstr_length(current));
409 print_cc('\b', wstr_length(current));
410
411 if (ch == U_UP_ARROW) {
412 /* Up */
413 if (history_pos == 0)
414 history_pos = KCONSOLE_HISTORY - 1;
415 else
416 history_pos--;
417 } else {
418 /* Down */
419 history_pos++;
420 history_pos = history_pos % KCONSOLE_HISTORY;
421 }
422 current = history[history_pos];
423 printf("%ls", current);
424 position = wstr_length(current);
425 continue;
426 }
427
428 if (ch == U_HOME_ARROW) {
429 /* Home */
430 print_cc('\b', position);
431 position = 0;
432 continue;
433 }
434
435 if (ch == U_END_ARROW) {
436 /* End */
437 printf("%ls", current + position);
438 position = wstr_length(current);
439 continue;
440 }
441
442 if (ch == U_DELETE) {
443 /* Delete */
444 if (position == wstr_length(current))
445 continue;
446
447 if (wstr_remove(current, position)) {
448 printf("%ls ", current + position);
449 print_cc('\b', wstr_length(current) - position + 1);
450 }
451 continue;
452 }
453
454 if (wstr_linsert(current, ch, position, MAX_CMDLINE)) {
455 printf("%ls", current + position);
456 position++;
457 print_cc('\b', wstr_length(current) - position);
458 }
459 }
460
461 if (wstr_length(current) > 0) {
462 history_pos++;
463 history_pos = history_pos % KCONSOLE_HISTORY;
464 }
465
466 free(tmp);
467 return current;
468}
469
470bool kconsole_check_poll(void)
471{
472 return check_poll(stdin);
473}
474
475NO_TRACE static bool parse_int_arg(const char *text, size_t len,
476 sysarg_t *result)
477{
478 bool isaddr = false;
479 bool isptr = false;
480
481 /* If we get a name, try to find it in symbol table */
482 if (text[0] == '&') {
483 isaddr = true;
484 text++;
485 len--;
486 } else if (text[0] == '*') {
487 isptr = true;
488 text++;
489 len--;
490 }
491
492 if ((text[0] < '0') || (text[0] > '9')) {
493 char symname[MAX_SYMBOL_NAME];
494 str_ncpy(symname, MAX_SYMBOL_NAME, text, len + 1);
495
496 uintptr_t symaddr;
497 int rc = symtab_addr_lookup(symname, &symaddr);
498 switch (rc) {
499 case ENOENT:
500 printf("Symbol %s not found.\n", symname);
501 return false;
502 case EOVERFLOW:
503 printf("Duplicate symbol %s.\n", symname);
504 symtab_print_search(symname);
505 return false;
506 case ENOTSUP:
507 printf("No symbol information available.\n");
508 return false;
509 case EOK:
510 if (isaddr)
511 *result = (sysarg_t) symaddr;
512 else if (isptr)
513 *result = **((sysarg_t **) symaddr);
514 else
515 *result = *((sysarg_t *) symaddr);
516 break;
517 default:
518 printf("Unknown error.\n");
519 return false;
520 }
521 } else {
522 /* It's a number - convert it */
523 uint64_t value;
524 char *end;
525 int rc = str_uint64_t(text, &end, 0, false, &value);
526 if (end != text + len)
527 rc = EINVAL;
528 switch (rc) {
529 case EINVAL:
530 printf("Invalid number '%s'.\n", text);
531 return false;
532 case EOVERFLOW:
533 printf("Integer overflow in '%s'.\n", text);
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 parsing '%s'.\n", text);
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, link, cmd_info_t, hlp) {
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.