vasprintf.c 1.7 KB

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