vasprintf.c 1.6 KB

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