printf.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Implementation of cprintf console output for user environments,
  2. // based on printfmt() and the sys_cputs() system call.
  3. //
  4. // cprintf is a debugging statement, not a generic output statement.
  5. // It is very important that it always go to the console, especially when
  6. // debugging file descriptor code!
  7. #include <linux/unistd.h>
  8. #include "internal.h"
  9. // Collect up to PRINTBUF_SIZE characters into a buffer
  10. // and perform ONE system call to print all of them,
  11. // in order to make the lines output to the console atomic
  12. // and prevent interrupts from causing context switches
  13. // in the middle of a console output line and such.
  14. #define PRINTBUF_SIZE 64
  15. struct printbuf {
  16. int idx; // current buffer index
  17. int cnt; // total bytes printed so far
  18. char buf[PRINTBUF_SIZE];
  19. };
  20. struct sprintbuf {
  21. char *buf;
  22. char *ebuf;
  23. int cnt;
  24. };
  25. #define sys_cputs(fd, bf, cnt) INLINE_SYSCALL(write, 3, (fd), (bf), (cnt))
  26. static int
  27. fputch(int fd, int ch, struct printbuf *b)
  28. {
  29. b->buf[b->idx++] = ch;
  30. if (b->idx == PRINTBUF_SIZE - 1) {
  31. sys_cputs(fd, b->buf, b->idx);
  32. b->idx = 0;
  33. }
  34. b->cnt++;
  35. return 0;
  36. }
  37. static int
  38. vprintf(const char *fmt, va_list *ap)
  39. {
  40. struct printbuf b;
  41. b.idx = 0;
  42. b.cnt = 0;
  43. vfprintfmt((void *) &fputch, (void *) 1, &b, fmt, ap);
  44. sys_cputs(1, b.buf, b.idx);
  45. return b.cnt;
  46. }
  47. int
  48. printf(const char *fmt, ...)
  49. {
  50. va_list ap;
  51. int cnt;
  52. va_start(ap, fmt);
  53. cnt = vprintf(fmt, &ap);
  54. va_end(ap);
  55. return cnt;
  56. }