printf.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 void
  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. }
  36. static int
  37. vprintf(const char *fmt, va_list *ap)
  38. {
  39. struct printbuf b;
  40. b.idx = 0;
  41. b.cnt = 0;
  42. vfprintfmt((void *) &fputch, (void *) 1, &b, fmt, ap);
  43. sys_cputs(1, b.buf, b.idx);
  44. return b.cnt;
  45. }
  46. int
  47. printf(const char *fmt, ...)
  48. {
  49. va_list ap;
  50. int cnt;
  51. va_start(ap, fmt);
  52. cnt = vprintf(fmt, &ap);
  53. va_end(ap);
  54. return cnt;
  55. }