tty.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. /* Copyright (C) 2021 Rain */
  2. /* This file is part of XNIX. */
  3. /*
  4. XNIX is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) and later version.
  8. */
  9. /*
  10. XNIX is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. GNU General Public License for more details.
  14. */
  15. /*
  16. You should have received a copy of the GNU General Public License
  17. along with XNIX. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. #include <kernel/init.h>
  20. #include <kernel/errno.h>
  21. #include <kernel/types.h>
  22. #include <kernel/console.h>
  23. #include <kernel/schk.h>
  24. #include <kernel/vsprintf.h>
  25. #include <kernel/tty.h>
  26. #include <lib/string.h>
  27. #include <lib/fifo.h>
  28. static char buffer[256];
  29. /* read a character from tty (keyboard) with non-cooked */
  30. int tty_read(struct tty *tty, char *buf, size_t nbytes) {
  31. schk_init();
  32. if (!buf)
  33. return -EINVAL;
  34. if (!nbytes)
  35. return 0;
  36. /* it's read-only */
  37. if (!tty->input_fifo)
  38. /* read from stdout, or stderr */
  39. return -EINVAL;
  40. schk_leave();
  41. return -EIO;
  42. }
  43. int tty_write(struct tty *tty, char *buf, size_t nbytes) {
  44. schk_init();
  45. if (!buf)
  46. return -EINVAL;
  47. if (!nbytes)
  48. return 0;
  49. int i;
  50. for (i = 0; i < nbytes; i++) {
  51. if (!buf[i])
  52. return i;
  53. tty->putc(tty, buf[i]);
  54. }
  55. schk_leave();
  56. return i;
  57. }
  58. int printk(__uint8_t color, char *s, ...) {
  59. va_list args;
  60. int i;
  61. /* I think 256 is enough in kernel */
  62. /* too long, return it. */
  63. va_start(args, s);
  64. /* it maybe overflow, but that's in .data section and we did check. */
  65. i = vsprintf(buffer, s, args);
  66. print(color, buffer);
  67. memset(buffer, 0, 256);
  68. va_end(args);
  69. return i;
  70. }
  71. void print(__uint8_t color, char *s) {
  72. while (*s)
  73. putc(*s++, color);
  74. return;
  75. }