__printf.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. * Copyright (c) 1997, 1998, 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009
  3. * The President and Fellows of Harvard College.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. * 1. Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in the
  12. * documentation and/or other materials provided with the distribution.
  13. * 3. Neither the name of the University nor the names of its contributors
  14. * may be used to endorse or promote products derived from this software
  15. * without specific prior written permission.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND
  18. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  20. * ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  23. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  24. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  25. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  26. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  27. * SUCH DAMAGE.
  28. */
  29. /*
  30. * Guts of printf.
  31. *
  32. * This file is used in both libc and the kernel and needs to work in both
  33. * contexts. This makes a few things a bit awkward.
  34. *
  35. * This is a slightly simplified version of the real-life printf
  36. * originally used in the VINO kernel.
  37. */
  38. #ifdef _KERNEL
  39. #include <types.h>
  40. #include <lib.h>
  41. #define assert KASSERT
  42. #else
  43. #include <sys/types.h>
  44. #include <assert.h>
  45. #include <stdint.h>
  46. #include <stdio.h>
  47. #include <string.h>
  48. #endif
  49. #include <stdarg.h>
  50. /*
  51. * Do we want to support "long long" types with %lld?
  52. *
  53. * Using 64-bit types with gcc causes gcc to emit calls to functions
  54. * like __moddi3 and __divdi3. These need to be provided at link time,
  55. * which can be a hassle; this switch is provided to help avoid
  56. * needing them.
  57. */
  58. #define USE_LONGLONG
  59. /*
  60. * Define a type that holds the longest signed integer we intend to support.
  61. */
  62. #ifdef USE_LONGLONG
  63. #define INTTYPE long long
  64. #else
  65. #define INTTYPE long
  66. #endif
  67. /*
  68. * Space for a long long in base 8, plus a NUL, plus one
  69. * character extra for slop.
  70. *
  71. * CHAR_BIT is the number of bits in a char; thus sizeof(long long)*CHAR_BIT
  72. * is the number of bits in a long long. Each octal digit prints 3 bits.
  73. * Values printed in larger bases will be shorter strings.
  74. */
  75. #define NUMBER_BUF_SIZE ((sizeof(INTTYPE) * CHAR_BIT) / 3 + 2)
  76. /*
  77. * Structure holding the state for printf.
  78. */
  79. typedef struct {
  80. /* Callback for sending printed string data */
  81. void (*sendfunc)(void *clientdata, const char *str, size_t len);
  82. void *clientdata;
  83. /* The varargs argument pointer */
  84. va_list ap;
  85. /* Total count of characters printed */
  86. int charcount;
  87. /* Flag that's true if we are currently looking in a %-format */
  88. int in_pct;
  89. /* Size of the integer argument to retrieve */
  90. enum {
  91. INTSZ,
  92. LONGSZ,
  93. #ifdef USE_LONGLONG
  94. LLONGSZ,
  95. #endif
  96. } size;
  97. /* The value of the integer argument retrieved */
  98. unsigned INTTYPE num;
  99. /* Sign of the integer argument (0 = positive; -1 = negative) */
  100. int sign;
  101. /* Field width (number of spaces) */
  102. int spacing;
  103. /* Flag: align to left in field instead of right */
  104. int rightspc;
  105. /* Character to pad to field size with (space or 0) */
  106. int fillchar;
  107. /* Number base to print the integer argument in (8, 10, 16) */
  108. int base;
  109. /* Flag: if set, print 0x before hex and 0 before octal numbers */
  110. int baseprefix;
  111. /* Flag: alternative output format selected with %#... */
  112. int altformat;
  113. } PF;
  114. /*
  115. * Send some text onward to the output.
  116. *
  117. * We count the total length we send out so we can return it from __vprintf,
  118. * since that's what most printf-like functions want to return.
  119. */
  120. static
  121. void
  122. __pf_print(PF *pf, const char *txt, size_t len)
  123. {
  124. pf->sendfunc(pf->clientdata, txt, len);
  125. pf->charcount += len;
  126. }
  127. /*
  128. * Reset the state for the next %-field.
  129. */
  130. static
  131. void
  132. __pf_endfield(PF *pf)
  133. {
  134. pf->in_pct = 0;
  135. pf->size = INTSZ;
  136. pf->num = 0;
  137. pf->sign = 0;
  138. pf->spacing = 0;
  139. pf->rightspc = 0;
  140. pf->fillchar = ' ';
  141. pf->base = 0;
  142. pf->baseprefix = 0;
  143. pf->altformat = 0;
  144. }
  145. /*
  146. * Process modifier chars (between the % and the type specifier)
  147. * # use "alternate display format"
  148. * - left align in field instead of right align
  149. * l value is long (ll = long long)
  150. * 0-9 field width
  151. * leading 0 pad with zeros instead of spaces
  152. */
  153. static
  154. void
  155. __pf_modifier(PF *pf, int ch)
  156. {
  157. switch (ch) {
  158. case '#':
  159. pf->altformat = 1;
  160. break;
  161. case '-':
  162. pf->rightspc = 1;
  163. break;
  164. case 'l':
  165. if (pf->size==LONGSZ) {
  166. #ifdef USE_LONGLONG
  167. pf->size = LLONGSZ;
  168. #endif
  169. }
  170. else {
  171. pf->size = LONGSZ;
  172. }
  173. break;
  174. case '0':
  175. if (pf->spacing>0) {
  176. /*
  177. * Already seen some digits; this is part of the
  178. * field size.
  179. */
  180. pf->spacing = pf->spacing*10;
  181. }
  182. else {
  183. /*
  184. * Leading zero; set the padding character to 0.
  185. */
  186. pf->fillchar = '0';
  187. }
  188. break;
  189. default:
  190. /*
  191. * Invalid characters should be filtered out by a
  192. * higher-level function, so if this assert goes off
  193. * it's our fault.
  194. */
  195. assert(ch>'0' && ch<='9');
  196. /*
  197. * Got a digit; accumulate the field size.
  198. */
  199. pf->spacing = pf->spacing*10 + (ch-'0');
  200. break;
  201. }
  202. }
  203. /*
  204. * Retrieve a numeric argument from the argument list and store it
  205. * in pf->num, according to the size recorded in pf->size and using
  206. * the numeric type specified by ch.
  207. */
  208. static
  209. void
  210. __pf_getnum(PF *pf, int ch)
  211. {
  212. if (ch=='p') {
  213. /*
  214. * Pointer.
  215. *
  216. * uintptr_t is a C99 standard type that's an unsigned
  217. * integer the same size as a pointer.
  218. */
  219. pf->num = (uintptr_t) va_arg(pf->ap, void *);
  220. }
  221. else if (ch=='d') {
  222. /* signed integer */
  223. INTTYPE signednum=0;
  224. switch (pf->size) {
  225. case INTSZ:
  226. /* %d */
  227. signednum = va_arg(pf->ap, int);
  228. break;
  229. case LONGSZ:
  230. /* %ld */
  231. signednum = va_arg(pf->ap, long);
  232. break;
  233. #ifdef USE_LONGLONG
  234. case LLONGSZ:
  235. /* %lld */
  236. signednum = va_arg(pf->ap, long long);
  237. break;
  238. #endif
  239. }
  240. /*
  241. * Check for negative numbers.
  242. */
  243. if (signednum < 0) {
  244. pf->sign = -1;
  245. pf->num = -signednum;
  246. }
  247. else {
  248. pf->num = signednum;
  249. }
  250. }
  251. else {
  252. /* unsigned integer */
  253. switch (pf->size) {
  254. case INTSZ:
  255. /* %u (or %o, %x) */
  256. pf->num = va_arg(pf->ap, unsigned int);
  257. break;
  258. case LONGSZ:
  259. /* %lu (or %lo, %lx) */
  260. pf->num = va_arg(pf->ap, unsigned long);
  261. break;
  262. #ifdef USE_LONGLONG
  263. case LLONGSZ:
  264. /* %llu, %llo, %llx */
  265. pf->num = va_arg(pf->ap, unsigned long long);
  266. break;
  267. #endif
  268. }
  269. }
  270. }
  271. /*
  272. * Set the printing base based on the numeric type specified in ch.
  273. * %o octal
  274. * %d,%u decimal
  275. * %x hex
  276. * %p pointer (print as hex)
  277. *
  278. * If the "alternate format" was requested, or always for pointers,
  279. * note to print the C prefix for the type.
  280. */
  281. static
  282. void
  283. __pf_setbase(PF *pf, int ch)
  284. {
  285. switch (ch) {
  286. case 'd':
  287. case 'u':
  288. pf->base = 10;
  289. break;
  290. case 'x':
  291. case 'p':
  292. pf->base = 16;
  293. break;
  294. case 'o':
  295. pf->base = 8;
  296. break;
  297. }
  298. if (pf->altformat || ch=='p') {
  299. pf->baseprefix = 1;
  300. }
  301. }
  302. /*
  303. * Function to print "spc" instances of the fill character.
  304. */
  305. static
  306. void
  307. __pf_fill(PF *pf, int spc)
  308. {
  309. char f = pf->fillchar;
  310. int i;
  311. for (i=0; i<spc; i++) {
  312. __pf_print(pf, &f, 1);
  313. }
  314. }
  315. /*
  316. * General printing function. Prints the string "stuff".
  317. * The two prefixes (in practice one is a type prefix, such as "0x",
  318. * and the other is the sign) get printed *after* space padding but
  319. * *before* zero padding, if padding is on the left.
  320. */
  321. static
  322. void
  323. __pf_printstuff(PF *pf,
  324. const char *prefix, const char *prefix2,
  325. const char *stuff)
  326. {
  327. /* Total length to print. */
  328. int len = strlen(prefix)+strlen(prefix2)+strlen(stuff);
  329. /* Get field width and compute amount of padding in "spc". */
  330. int spc = pf->spacing;
  331. if (spc > len) {
  332. spc -= len;
  333. }
  334. else {
  335. spc = 0;
  336. }
  337. /* If padding on left and the fill char is not 0, pad first. */
  338. if (spc > 0 && pf->rightspc==0 && pf->fillchar!='0') {
  339. __pf_fill(pf, spc);
  340. }
  341. /* Print the prefixes. */
  342. __pf_print(pf, prefix, strlen(prefix));
  343. __pf_print(pf, prefix2, strlen(prefix2));
  344. /* If padding on left and the fill char *is* 0, pad here. */
  345. if (spc > 0 && pf->rightspc==0 && pf->fillchar=='0') {
  346. __pf_fill(pf, spc);
  347. }
  348. /* Print the actual string. */
  349. __pf_print(pf, stuff, strlen(stuff));
  350. /* If padding on the right, pad afterwards. */
  351. if (spc > 0 && pf->rightspc!=0) {
  352. __pf_fill(pf, spc);
  353. }
  354. }
  355. /*
  356. * Function to convert a number to ascii and then print it.
  357. *
  358. * Works from right to left in a buffer of NUMBER_BUF_SIZE bytes.
  359. * NUMBER_BUF_SIZE is set so that the longest number string we can
  360. * generate (a long long printed in octal) will fit. See above.
  361. */
  362. static
  363. void
  364. __pf_printnum(PF *pf)
  365. {
  366. /* Digits to print with. */
  367. const char *const digits = "0123456789abcdef";
  368. char buf[NUMBER_BUF_SIZE]; /* Accumulation buffer for string. */
  369. char *x; /* Current pointer into buf. */
  370. unsigned INTTYPE xnum; /* Current value to print. */
  371. const char *bprefix; /* Base prefix (0, 0x, or nothing) */
  372. const char *sprefix; /* Sign prefix (- or nothing) */
  373. /* Start in the last slot of the buffer. */
  374. x = buf+sizeof(buf)-1;
  375. /* Insert null terminator. */
  376. *x-- = 0;
  377. /* Initialize value. */
  378. xnum = pf->num;
  379. /*
  380. * Convert a single digit.
  381. * Do this loop at least once - that way 0 prints as 0 and not "".
  382. */
  383. do {
  384. /*
  385. * Get the digit character for the least significant
  386. * part of xnum.
  387. */
  388. *x = digits[xnum % pf->base];
  389. /*
  390. * Back up the pointer to point to the next space to the left.
  391. */
  392. x--;
  393. /*
  394. * Drop the value of the digit we just printed from xnum.
  395. */
  396. xnum = xnum / pf->base;
  397. /*
  398. * If xnum hits 0 there's no more number left.
  399. */
  400. } while (xnum > 0);
  401. /*
  402. * x points to the *next* slot in the buffer to use.
  403. * However, we're done printing the number. So it's pointing
  404. * one slot *before* the start of the actual number text.
  405. * So advance it by one so it actually points at the number.
  406. */
  407. x++;
  408. /*
  409. * If a base prefix was requested, select it.
  410. */
  411. if (pf->baseprefix && pf->base==16) {
  412. bprefix = "0x";
  413. }
  414. else if (pf->baseprefix && pf->base==8) {
  415. bprefix = "0";
  416. }
  417. else {
  418. bprefix = "";
  419. }
  420. /*
  421. * Choose the sign prefix.
  422. */
  423. sprefix = pf->sign ? "-" : "";
  424. /*
  425. * Now actually print the string we just generated.
  426. */
  427. __pf_printstuff(pf, sprefix, bprefix, x);
  428. }
  429. /*
  430. * Process a single character out of the format string.
  431. */
  432. static
  433. void
  434. __pf_send(PF *pf, int ch)
  435. {
  436. /* Cannot get NULs here. */
  437. assert(ch!=0);
  438. if (pf->in_pct==0 && ch!='%') {
  439. /*
  440. * Not currently in a format, and not a %. Just send
  441. * the character on through.
  442. */
  443. char c = ch;
  444. __pf_print(pf, &c, 1);
  445. }
  446. else if (pf->in_pct==0) {
  447. /*
  448. * Not in a format, but got a %. Start a format.
  449. */
  450. pf->in_pct = 1;
  451. }
  452. else if (strchr("#-l0123456789", ch)) {
  453. /*
  454. * These are the modifier characters we recognize.
  455. * (These are the characters between the % and the type.)
  456. */
  457. __pf_modifier(pf, ch);
  458. }
  459. else if (strchr("doupx", ch)) {
  460. /*
  461. * Integer types.
  462. * Fetch the number, set the base, print it, then
  463. * reset for the next format.
  464. */
  465. __pf_getnum(pf, ch);
  466. __pf_setbase(pf, ch);
  467. __pf_printnum(pf);
  468. __pf_endfield(pf);
  469. }
  470. else if (ch=='s') {
  471. /*
  472. * Print a string.
  473. */
  474. const char *str = va_arg(pf->ap, const char *);
  475. if (str==NULL) {
  476. str = "(null)";
  477. }
  478. __pf_printstuff(pf, "", "", str);
  479. __pf_endfield(pf);
  480. }
  481. else {
  482. /*
  483. * %%, %c, or illegal character.
  484. * Illegal characters are printed like %%.
  485. * for example, %5k prints " k".
  486. */
  487. char x[2];
  488. if (ch=='c') {
  489. x[0] = va_arg(pf->ap, int);
  490. }
  491. else {
  492. x[0] = ch;
  493. }
  494. x[1] = 0;
  495. __pf_printstuff(pf, "", "", x);
  496. __pf_endfield(pf);
  497. }
  498. }
  499. /*
  500. * Do a whole printf session.
  501. * Create and initialize a printf state object,
  502. * then send it each character from the format string.
  503. */
  504. int
  505. __vprintf(void (*func)(void *clientdata, const char *str, size_t len),
  506. void *clientdata, const char *format, va_list ap)
  507. {
  508. PF pf;
  509. int i;
  510. pf.sendfunc = func;
  511. pf.clientdata = clientdata;
  512. pf.ap = ap;
  513. pf.charcount = 0;
  514. __pf_endfield(&pf);
  515. for (i=0; format[i]; i++) {
  516. __pf_send(&pf, format[i]);
  517. }
  518. return pf.charcount;
  519. }