argv_split.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Helper function for splitting a string into an argv-like array.
  4. */
  5. #include <linux/kernel.h>
  6. #include <linux/ctype.h>
  7. #include <linux/string.h>
  8. #include <linux/slab.h>
  9. #include <linux/export.h>
  10. static int count_argc(const char *str)
  11. {
  12. int count = 0;
  13. bool was_space;
  14. for (was_space = true; *str; str++) {
  15. if (isspace(*str)) {
  16. was_space = true;
  17. } else if (was_space) {
  18. was_space = false;
  19. count++;
  20. }
  21. }
  22. return count;
  23. }
  24. /**
  25. * argv_free - free an argv
  26. * @argv - the argument vector to be freed
  27. *
  28. * Frees an argv and the strings it points to.
  29. */
  30. void argv_free(char **argv)
  31. {
  32. argv--;
  33. kfree(argv[0]);
  34. kfree(argv);
  35. }
  36. EXPORT_SYMBOL(argv_free);
  37. /**
  38. * argv_split - split a string at whitespace, returning an argv
  39. * @gfp: the GFP mask used to allocate memory
  40. * @str: the string to be split
  41. * @argcp: returned argument count
  42. *
  43. * Returns an array of pointers to strings which are split out from
  44. * @str. This is performed by strictly splitting on white-space; no
  45. * quote processing is performed. Multiple whitespace characters are
  46. * considered to be a single argument separator. The returned array
  47. * is always NULL-terminated. Returns NULL on memory allocation
  48. * failure.
  49. *
  50. * The source string at `str' may be undergoing concurrent alteration via
  51. * userspace sysctl activity (at least). The argv_split() implementation
  52. * attempts to handle this gracefully by taking a local copy to work on.
  53. */
  54. char **argv_split(gfp_t gfp, const char *str, int *argcp)
  55. {
  56. char *argv_str;
  57. bool was_space;
  58. char **argv, **argv_ret;
  59. int argc;
  60. argv_str = kstrndup(str, KMALLOC_MAX_SIZE - 1, gfp);
  61. if (!argv_str)
  62. return NULL;
  63. argc = count_argc(argv_str);
  64. argv = kmalloc_array(argc + 2, sizeof(*argv), gfp);
  65. if (!argv) {
  66. kfree(argv_str);
  67. return NULL;
  68. }
  69. *argv = argv_str;
  70. argv_ret = ++argv;
  71. for (was_space = true; *argv_str; argv_str++) {
  72. if (isspace(*argv_str)) {
  73. was_space = true;
  74. *argv_str = 0;
  75. } else if (was_space) {
  76. was_space = false;
  77. *argv++ = argv_str;
  78. }
  79. }
  80. *argv = NULL;
  81. if (argcp)
  82. *argcp = argc;
  83. return argv_ret;
  84. }
  85. EXPORT_SYMBOL(argv_split);