mysnprintf.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #include "Python.h"
  2. /* snprintf() and vsnprintf() wrappers.
  3. If the platform has vsnprintf, we use it, else we
  4. emulate it in a half-hearted way. Even if the platform has it, we wrap
  5. it because platforms differ in what vsnprintf does in case the buffer
  6. is too small: C99 behavior is to return the number of characters that
  7. would have been written had the buffer not been too small, and to set
  8. the last byte of the buffer to \0. At least MS _vsnprintf returns a
  9. negative value instead, and fills the entire buffer with non-\0 data.
  10. Unlike C99, our wrappers do not support passing a null buffer.
  11. The wrappers ensure that str[size-1] is always \0 upon return.
  12. PyOS_snprintf and PyOS_vsnprintf never write more than size bytes
  13. (including the trailing '\0') into str.
  14. Return value (rv):
  15. When 0 <= rv < size, the output conversion was unexceptional, and
  16. rv characters were written to str (excluding a trailing \0 byte at
  17. str[rv]).
  18. When rv >= size, output conversion was truncated, and a buffer of
  19. size rv+1 would have been needed to avoid truncation. str[size-1]
  20. is \0 in this case.
  21. When rv < 0, "something bad happened". str[size-1] is \0 in this
  22. case too, but the rest of str is unreliable. It could be that
  23. an error in format codes was detected by libc, or on platforms
  24. with a non-C99 vsnprintf simply that the buffer wasn't big enough
  25. to avoid truncation, or on platforms without any vsnprintf that
  26. PyMem_Malloc couldn't obtain space for a temp buffer.
  27. CAUTION: Unlike C99, str != NULL and size > 0 are required.
  28. Also, size must be smaller than INT_MAX.
  29. */
  30. int
  31. PyOS_snprintf(char *str, size_t size, const char *format, ...)
  32. {
  33. int rc;
  34. va_list va;
  35. va_start(va, format);
  36. rc = PyOS_vsnprintf(str, size, format, va);
  37. va_end(va);
  38. return rc;
  39. }
  40. int
  41. PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
  42. {
  43. assert(str != NULL);
  44. assert(size > 0);
  45. assert(size <= (INT_MAX - 1));
  46. assert(format != NULL);
  47. int len; /* # bytes written, excluding \0 */
  48. /* We take a size_t as input but return an int. Sanity check
  49. * our input so that it won't cause an overflow in the
  50. * vsnprintf return value. */
  51. if (size > INT_MAX - 1) {
  52. len = -666;
  53. goto Done;
  54. }
  55. #if defined(_MSC_VER)
  56. len = _vsnprintf(str, size, format, va);
  57. #else
  58. len = vsnprintf(str, size, format, va);
  59. #endif
  60. Done:
  61. if (size > 0) {
  62. str[size-1] = '\0';
  63. }
  64. return len;
  65. }