vasprintf.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. #ifdef __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__
  18. libc_hidden_proto(open_memstream)
  19. libc_hidden_proto(fclose)
  20. libc_hidden_proto(vfprintf)
  21. #else
  22. libc_hidden_proto(vsnprintf)
  23. #endif
  24. libc_hidden_proto(vasprintf)
  25. int vasprintf(char **__restrict buf, const char * __restrict format,
  26. va_list arg)
  27. {
  28. #ifdef __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__
  29. FILE *f;
  30. size_t size;
  31. int rv = -1;
  32. *buf = NULL;
  33. if ((f = open_memstream(buf, &size)) != NULL) {
  34. rv = vfprintf(f, format, arg);
  35. fclose(f);
  36. if (rv < 0) {
  37. free(*buf);
  38. *buf = NULL;
  39. }
  40. }
  41. assert(rv >= -1);
  42. return rv;
  43. #else /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  44. /* This implementation actually calls the printf machinery twice, but only
  45. * only does one malloc. This can be a problem though when custom printf
  46. * specs or the %m specifier are involved because the results of the
  47. * second call might be different from the first. */
  48. va_list arg2;
  49. int rv;
  50. va_copy(arg2, arg);
  51. rv = vsnprintf(NULL, 0, format, arg2);
  52. va_end(arg2);
  53. *buf = NULL;
  54. if (rv >= 0) {
  55. if ((*buf = malloc(++rv)) != NULL) {
  56. if ((rv = vsnprintf(*buf, rv, format, arg)) < 0) {
  57. free(*buf);
  58. *buf = NULL;
  59. }
  60. }
  61. }
  62. assert(rv >= -1);
  63. return rv;
  64. #endif /* __UCLIBC_HAS_GLIBC_CUSTOM_STREAMS__ */
  65. }
  66. libc_hidden_def(vasprintf)
  67. #endif