kasprintf.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * linux/lib/kasprintf.c
  3. *
  4. * Copyright (C) 1991, 1992 Linus Torvalds
  5. */
  6. #include <stdarg.h>
  7. #include <linux/export.h>
  8. #include <linux/slab.h>
  9. #include <linux/types.h>
  10. #include <linux/string.h>
  11. /* Simplified asprintf. */
  12. char *kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
  13. {
  14. unsigned int first, second;
  15. char *p;
  16. va_list aq;
  17. va_copy(aq, ap);
  18. first = vsnprintf(NULL, 0, fmt, aq);
  19. va_end(aq);
  20. p = kmalloc_track_caller(first+1, gfp);
  21. if (!p)
  22. return NULL;
  23. second = vsnprintf(p, first+1, fmt, ap);
  24. WARN(first != second, "different return values (%u and %u) from vsnprintf(\"%s\", ...)",
  25. first, second, fmt);
  26. return p;
  27. }
  28. EXPORT_SYMBOL(kvasprintf);
  29. /*
  30. * If fmt contains no % (or is exactly %s), use kstrdup_const. If fmt
  31. * (or the sole vararg) points to rodata, we will then save a memory
  32. * allocation and string copy. In any case, the return value should be
  33. * freed using kfree_const().
  34. */
  35. const char *kvasprintf_const(gfp_t gfp, const char *fmt, va_list ap)
  36. {
  37. if (!strchr(fmt, '%'))
  38. return kstrdup_const(fmt, gfp);
  39. if (!strcmp(fmt, "%s"))
  40. return kstrdup_const(va_arg(ap, const char*), gfp);
  41. return kvasprintf(gfp, fmt, ap);
  42. }
  43. EXPORT_SYMBOL(kvasprintf_const);
  44. char *kasprintf(gfp_t gfp, const char *fmt, ...)
  45. {
  46. va_list ap;
  47. char *p;
  48. va_start(ap, fmt);
  49. p = kvasprintf(gfp, fmt, ap);
  50. va_end(ap);
  51. return p;
  52. }
  53. EXPORT_SYMBOL(kasprintf);