kasprintf.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 len;
  15. char *p;
  16. va_list aq;
  17. va_copy(aq, ap);
  18. len = vsnprintf(NULL, 0, fmt, aq);
  19. va_end(aq);
  20. p = kmalloc_track_caller(len+1, gfp);
  21. if (!p)
  22. return NULL;
  23. vsnprintf(p, len+1, fmt, ap);
  24. return p;
  25. }
  26. EXPORT_SYMBOL(kvasprintf);
  27. /*
  28. * If fmt contains no % (or is exactly %s), use kstrdup_const. If fmt
  29. * (or the sole vararg) points to rodata, we will then save a memory
  30. * allocation and string copy. In any case, the return value should be
  31. * freed using kfree_const().
  32. */
  33. const char *kvasprintf_const(gfp_t gfp, const char *fmt, va_list ap)
  34. {
  35. if (!strchr(fmt, '%'))
  36. return kstrdup_const(fmt, gfp);
  37. if (!strcmp(fmt, "%s"))
  38. return kstrdup_const(va_arg(ap, const char*), gfp);
  39. return kvasprintf(gfp, fmt, ap);
  40. }
  41. EXPORT_SYMBOL(kvasprintf_const);
  42. char *kasprintf(gfp_t gfp, const char *fmt, ...)
  43. {
  44. va_list ap;
  45. char *p;
  46. va_start(ap, fmt);
  47. p = kvasprintf(gfp, fmt, ap);
  48. va_end(ap);
  49. return p;
  50. }
  51. EXPORT_SYMBOL(kasprintf);