vsprintf.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /* kernel/vsprintf.c
  2. *
  3. * This file is part of evx.
  4. *
  5. * evx is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * evx 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. * You should have received a copy of the GNU General Public License
  16. * along with evx. If not, see <https://www.gnu.org/licenses/>
  17. */
  18. #include <kernel/init.h>
  19. #include <kernel/module.h>
  20. #include <kernel/kernel.h>
  21. #include <sys/types.h>
  22. #include <stdarg.h>
  23. int cano_putc(int);
  24. int printk(char *s, ...) {
  25. /* 512 bytes are enough for kernel, because kernelers are
  26. * very very good, I think :-)
  27. *
  28. * but you must know this truth, because more long 's' can
  29. * make a stack-overflow */
  30. char buf[512];
  31. va_list args;
  32. int i;
  33. va_start(args, s);
  34. i = vsprintf(buf, s, args);
  35. va_end(args);
  36. for (i = 0; buf[i]; i++)
  37. /* will be changed by tty_write etc. in the future */
  38. cano_putc(buf[i]);
  39. return i;
  40. }
  41. /* the function used to format a string, using stdargs */
  42. #define output(c) buf[bufindex++] = c
  43. int vsprintf(char *buf, const char *s, va_list args) {
  44. int i, c, state = 0, bufindex;
  45. char *t;
  46. bufindex = 0;
  47. for (i = 0; (c = s[i]); i++) {
  48. if (c == '%') {
  49. if (unlikely(!state))
  50. state = 1;
  51. else
  52. state = 0;
  53. continue;
  54. }
  55. else if (likely(!state)) {
  56. output(c);
  57. continue;
  58. }
  59. switch (c) {
  60. case 'c':
  61. output(va_arg(args, int));
  62. break;
  63. case 's':
  64. t = va_arg(args, char *);
  65. while (*t)
  66. output(*t++);
  67. break;
  68. default:
  69. output('E');
  70. (void) va_arg(args, int);
  71. break;
  72. }
  73. state = 0;
  74. }
  75. return i;
  76. }