vasprintf.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  34. }
  35. assert(rv >= -1);
  36. return rv;
  37. #else /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  38. /* This implementation actually calls the printf machinery twice, but
  39. * only does one malloc. This can be a problem though when custom printf
  40. * specs or the %m specifier are involved because the results of the
  41. * second call might be different from the first. */
  42. va_list arg2;
  43. int rv;
  44. va_copy(arg2, arg);
  45. rv = vsnprintf(NULL, 0, format, arg2);
  46. va_end(arg2);
  47. *buf = NULL;
  48. if (rv >= 0) {
  49. if ((*buf = malloc(++rv)) != NULL) {
  50. if ((rv = vsnprintf(*buf, rv, format, arg)) < 0) {
  51. free(*buf);
  52. *buf = NULL;
  53. }
  54. }
  55. }
  56. assert(rv >= -1);
  57. return rv;
  58. #endif /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  59. }
  60. libc_hidden_def(vasprintf)
  61. #endif
  62. #endif