vasprintf.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Copyright (C) 2004 Manuel Novoa III <mjn3@codepoet.org>
  2. *
  3. * GNU Library General Public License (LGPL) version 2 or later.
  4. *
  5. * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details.
  6. */
  7. #include "_stdio.h"
  8. #include <stdarg.h>
  9. #include <bits/uClibc_va_copy.h>
  10. #ifdef __UCLIBC_MJN3_ONLY__
  11. /* Do the memstream stuff inline to avoid fclose and the openlist? */
  12. #warning CONSIDER: avoid open_memstream call?
  13. #endif
  14. #ifndef __STDIO_HAS_VSNPRINTF
  15. #warning Skipping vasprintf since no vsnprintf!
  16. #else
  17. int vasprintf(char **__restrict buf, const char * __restrict format,
  18. va_list arg)
  19. {
  20. #ifdef __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__
  21. FILE *f;
  22. size_t size;
  23. int rv = -1;
  24. *buf = NULL;
  25. if ((f = open_memstream(buf, &size)) != NULL) {
  26. rv = vfprintf(f, format, arg);
  27. fclose(f);
  28. if (rv < 0) {
  29. free(*buf);
  30. *buf = NULL;
  31. }
  32. }
  33. assert(rv >= -1);
  34. return rv;
  35. #else /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  36. /* This implementation actually calls the printf machinery twice, but only
  37. * only does one malloc. This can be a problem though when custom printf
  38. * specs or the %m specifier are involved because the results of the
  39. * second call might be different from the first. */
  40. va_list arg2;
  41. int rv;
  42. va_copy(arg2, arg);
  43. rv = vsnprintf(NULL, 0, format, arg2);
  44. va_end(arg2);
  45. *buf = NULL;
  46. if (rv >= 0) {
  47. if ((*buf = malloc(++rv)) != NULL) {
  48. if ((rv = vsnprintf(*buf, rv, format, arg)) < 0) {
  49. free(*buf);
  50. *buf = NULL;
  51. }
  52. }
  53. }
  54. assert(rv >= -1);
  55. return rv;
  56. #endif /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  57. }
  58. #endif