vasprintf.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. #ifdef __UCLIBC_MJN3_ONLY__
  10. /* Do the memstream stuff inline to avoid fclose and the openlist? */
  11. #warning CONSIDER: avoid open_memstream call?
  12. #endif
  13. #ifndef __STDIO_HAS_VSNPRINTF
  14. #warning Skipping vasprintf since no vsnprintf!
  15. #else
  16. int vasprintf(char **__restrict buf, const char * __restrict format,
  17. va_list arg)
  18. {
  19. #ifdef __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__
  20. FILE *f;
  21. size_t size;
  22. int rv = -1;
  23. *buf = NULL;
  24. if ((f = open_memstream(buf, &size)) != NULL) {
  25. rv = vfprintf(f, format, arg);
  26. fclose(f);
  27. if (rv < 0) {
  28. free(*buf);
  29. *buf = NULL;
  30. }
  31. }
  32. assert(rv >= -1);
  33. return rv;
  34. #else /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  35. /* This implementation actually calls the printf machinery twice, but only
  36. * only does one malloc. This can be a problem though when custom printf
  37. * specs or the %m specifier are involved because the results of the
  38. * second call might be different from the first. */
  39. va_list arg2;
  40. int rv;
  41. va_copy(arg2, arg);
  42. rv = vsnprintf(NULL, 0, format, arg2);
  43. va_end(arg2);
  44. *buf = NULL;
  45. if (rv >= 0) {
  46. if ((*buf = malloc(++rv)) != NULL) {
  47. if ((rv = vsnprintf(*buf, rv, format, arg)) < 0) {
  48. free(*buf);
  49. *buf = NULL;
  50. }
  51. }
  52. }
  53. assert(rv >= -1);
  54. return rv;
  55. #endif /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  56. }
  57. #endif