printf.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 "utils.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. }
  56. static void
  57. sprintputch(int fd, int ch, struct sprintbuf * b)
  58. {
  59. b->cnt++;
  60. if (b->buf < b->ebuf)
  61. *b->buf++ = ch;
  62. }
  63. int
  64. vsprintf(char * buf, int n, const char * fmt, va_list ap)
  65. {
  66. struct sprintbuf b = {buf, buf + n - 1, 0};
  67. if (buf == NULL || n < 1) {
  68. return -1;
  69. }
  70. // print the string to the buffer
  71. vfprintfmt((void *) sprintputch, (void *) 0, &b, fmt, ap);
  72. // null terminate the buffer
  73. *b.buf = '\0';
  74. return b.cnt;
  75. }
  76. int
  77. snprintf(char * buf, size_t n, const char * fmt, ...)
  78. {
  79. va_list ap;
  80. int rc;
  81. va_start(ap, fmt);
  82. rc = vsprintf(buf, n, fmt, ap);
  83. va_end(ap);
  84. return rc;
  85. }